简体   繁体   English

点击时如何调整UIImageView的大小?

[英]How to resize the UIImageView when tapped on?

I am trying to play around with the UIImageView. 我正在尝试使用UIImageView。 I want something that when I tap the image, it makes the image 2x its size (always make it twice the size so if I tap more than once it keeps getting bigger). 我想要的东西是,当我点击图像时,它使图像的大小变成其两倍(总是使其变成两倍大小,所以如果我点击不止一次,它就会变得越来越大)。

This is what I currently have and I am not sure how to build the handlePan function that I originally wanted to use. 这是我目前拥有的,而且我不确定如何构建我最初想要使用的handlePan函数。 I used the pan gesture because I don't know how to approach the tap gesture specifically. 我使用了平移手势,因为我不知道如何具体接近轻击手势。 If my code is not on the right direction, please feel free to suggest what would work best. 如果我的代码没有正确的方向,请随时提出最有效的建议。 I would really appreciate any input. 我真的很感谢任何投入。

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var ImageView1: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let gesterRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) //handlePan is the tap function I am trying to build
        ImageView1.isUserInteractionEnabled = true
        ImageView1.addGestureRecognizer(gesterRecognizer)
    }
}

As mentioned in the comments, first of all you need a tap gesture recognizer instead of pan gesture one. 如评论中所述,首先您需要轻击手势识别器,而不是平移手势识别器。 In following code you will be able to double the width and height of image each time a user tap's on imageView. 在下面的代码中,每次用户在imageView上单击时,您都可以将图像的宽度和高度加倍。

In this implementation I wanted to animate the transition with 0.5 seconds, which is not necessary but it might look better to do it this way. 在此实现中,我希望以0.5秒为过渡设置动画,这不是必需的,但用这种方法看起来可能更好。 Also assuming that you want image to be at center at all times, you need to set center to frame's center so it wont float around as the frame of image changes. 同样,假设您希望图像始终处于中心位置,则需要将中心设置为框架的中心,这样它就不会随着图像框架的变化而浮动。 But if you wish to have a different layout or positioning, you need to update the following line: 但是,如果您希望使用其他布局或位置,则需要更新以下行:

self.imageView.center = self.view.center

Also you need to enable imageView's user interaction property, by setting it true. 另外,您需要通过将其设置为true来启用imageView的用户交互属性。

import UIKit

class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}


@objc func handleTap() {
    UIView.animate(withDuration: 0.5) {
        self.imageView.frame.size.height *= 2
        self.imageView.frame.size.width *= 2
        self.imageView.center = self.view.center
    }
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM