我试着在用户点击的时候分配一个UIImageView给一个动作。

我知道如何为一个UIButton创建一个动作,但我怎么能模仿一个UIButton相同的行为,但使用一个UIImageView?


当前回答

我建议在你的imageview上放置不可见(不透明度= 0)按钮,然后处理按钮上的交互。

其他回答

你需要添加一个手势识别器(对于点击使用UITapGestureRecognizer,对于点击和按住使用UILongPressGestureRecognizer)到你的UIImageView。

let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true

并像这样实现selector方法:

@objc func tappedMe()
{
    println("Tapped on Image")
}

需要添加懒TapGestureRecognizer注册 因为“self”在UITapGestureRecognizer(目标:self…)将是nil如果它不是一个惰性变量。即使你设置isUserInteractionEnable = true,它不会注册没有惰性变量。

lazy var imageSelector : UIImageView = {
    let image = UIImageView(image: "imageName.png")
    //now add tap gesture
    image.isUserInteractionEnabled = true
    image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
    return image
}()
@objc private func handleImageSelector() {
    print("Pressed image selector")
}

Swift 4代码


步骤1在ViewdidLoad()中

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

步骤2添加“Following”功能

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

它已经过测试,工作正常

你可以在UIImageView上面放一个带有透明背景的UIButton,并在加载图像之前监听按钮上的点击

我建议在你的imageview上放置不可见(不透明度= 0)按钮,然后处理按钮上的交互。