简体   繁体   English

你如何在 storyboard 上制作一个 UIImageView 可点击(快速)

[英]How do you make an UIImageView on the storyboard clickable (swift)

I am new to swift (and Xcode development in general) and I was wondering how to make an ImageView on the storyboard clickable.我是 swift(和一般的 Xcode 开发)的新手,我想知道如何使 storyboard 上的 ImageView 可点击。 What I'm trying to do is make it so when its clicked, it shows another view controller.我要做的是让它在单击时显示另一个视图 controller。

You can add tapGesture for that. 您可以为此添加tapGesture。 Here is the code: 这是代码:

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    // create tap gesture recognizer
    let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")

    // add it to the image view;
    imageView.addGestureRecognizer(tapGesture)
    // make sure imageView can be interacted with by user
    imageView.userInteractionEnabled = true
}

func imageTapped(gesture: UIGestureRecognizer) {
    // if the tapped view is a UIImageView then set it to imageview
    if let imageView = gesture.view as? UIImageView {
        println("Image Tapped")
        //Here you can initiate your new ViewController

        }
    }
}

Swift 3.0 Swift 3.0

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // create tap gesture recognizer
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.imageTapped(gesture:)))

        // add it to the image view;
        imageView.addGestureRecognizer(tapGesture)
        // make sure imageView can be interacted with by user
        imageView.isUserInteractionEnabled = true
    }

    func imageTapped(gesture: UIGestureRecognizer) {
        // if the tapped view is a UIImageView then set it to imageview
        if (gesture.view as? UIImageView) != nil {
            print("Image Tapped")
            //Here you can initiate your new ViewController

        }
    }
}

Swift 5.0 Swift 5.0

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // create tap gesture recognizer
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.imageTapped(gesture:)))

        // add it to the image view;
        imageView.addGestureRecognizer(tapGesture)
        // make sure imageView can be interacted with by user
        imageView.isUserInteractionEnabled = true
    }

    @objc func imageTapped(gesture: UIGestureRecognizer) {
        // if the tapped view is a UIImageView then set it to imageview
        if (gesture.view as? UIImageView) != nil {
            print("Image Tapped")
            //Here you can initiate your new ViewController

        }
    }
}

You can do it even easier and make a image clickable via Storyboard with no coding at all . 您可以更轻松地完成它,并通过Storyboard使图像可以点击,完全没有编码

  • First you need to drag a UITapGestureRecognizer onto your UIImageView in Storyboard. 首先,您需要将UITapGestureRecognizer拖到Storyboard中的UIImageView上。
  • Then you create the IBAction you want to run in your code with @IBAction func imageClicked(_ sender: Any) {} 然后使用@IBAction func imageClicked(_ sender: Any) {}创建要在代码中运行的IBAction @IBAction func imageClicked(_ sender: Any) {}
  • Next you need to connect the UITapGestureRecognizer to the IBAction in your class by selecting the gesture recognizer in the Document Outline , then switching to the Connection Inspector Tab and dragging the Sent Actions -> Selector to your UIViewController where you then select the appropriate action you created previously. 接下来,您需要通过在Document Outline选择手势识别器,然后切换到Connection Inspector Tab并将Sent Actions - > Selector拖到UIViewController ,然后选择您创建的相应操作,将UITapGestureRecognizer连接到UITapGestureRecognizer中的IBAction 。先前。
  • Finally you have to set the checkbox User Interaction Enabled on the image view. 最后,您必须在图像视图上设置“ User Interaction Enabled ”复选框。

Done, a fully clickable UIImageView without writing a single line of code except the obvious function you want to invoke. 完成,一个完全可点击的UIImageView,无需编写一行代码,除了您要调用的明显函数。 But hey, if you for example want to push a segue instead, then you can go without coding at all by using the gesture recognizers Triggered Segues instead of its Sent Actions . 但是,嘿,如果你想要推动一个segue,那么你可以通过使用手势识别器Triggered Segues而不是它的Sent Actions来完成编码。

Though Storyboard have their limitations, theres no need to write code for clickable images. 尽管Storyboard有其局限性,但无需为可点击图像编写代码。 ;) ;)

在此输入图像描述

I would suggest creating a UIButton with no text and making it the image you want, instead. 我建议创建一个没有文本的UIButton,并将其制作成您想要的图像。 After doing that, you can CTRL-drag from the image to the view controller you want to segue to. 执行此操作后,您可以从图像按CTRL拖动到要切换到的视图控制器。 Or you can just make an IBAction in your view controller's code that manually segues. 或者您可以在视图控制器的代码中进行IBAction手动分段。

for swift version 3.0 try below code 对于swift 3.0版,请尝试以下代码

override func viewDidLoad() {
super.viewDidLoad()

let tap1 = UITapGestureRecognizer(target: self, action: #selector(tapGesture1))
imageview.addGestureRecognizer(tap1)
imageview.isUserInteractionEnabled = true
}
func tapGesture1() {
    print("Image Tapped")
}

On the storyboard set image view user interaction enabled and then get with this method 在故事板上设置图像视图,启用用户交互,然后使用此方法

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];

    if ([touch view] == yourImageView)
    {
            //add your code for image touch here 
    }
}

Firstly, created one image view.首先,创建一个图像视图。 Than write this code override func viewDidLoad() { super.viewDidLoad()比写这段代码覆盖 func viewDidLoad() { super.viewDidLoad()

let tap = UITapGestureRecognizer(target: self, action:          #selector(tapGesture))
imageview.addGestureRecognizer(tap)
imageview.isUserInteractionEnabled = true
}
func tapGesture() {
    print("Image View Tapped")
}

in your view controller.在您看来 controller。

UITapGestureRecognizer method do everything is clickable UITapGestureRecognizer 方法做的一切都是可点击的

I achieved this by setting user interaction enable = true 我通过设置用户交互enable = true来实现这一点

and this code below in TouchesBegan... Clean and simple for this 以下代码在TouchesBegan中......干净简单

ImageView was also inside a StackView ImageView也在StackView中

if let touch = touches.first {
   if touch.view == profilePicture {
      print("image touched")
   }
}

Well, although you can use a UITapGestureRecognizer like mentioned above, if you need to do a quick project and just care about the functionality of the app, the easiest way is to have a transparent button covering your UIImageView with no text, and then using that to write whatever code you want. 好吧,虽然你可以使用上面提到的UITapGestureRecognizer,如果你需要做一个快速的项目,只关心应用程序的功能,最简单的方法是有一个透明的按钮覆盖你的UIImageView没有文字,然后使用写下你想要的任何代码。 Sure, this will not be recommended if you're making a very important project or something but if you just want to make a quick app (let's say a very simple MVP for some meeting) this method should work fine. 当然,如果您正在制作一个非常重要的项目或其他东西,但是如果您只想制作一个快速的应用程序(假设某个会议的MVP非常简单),这个方法应该可以正常工作。

in my opinion the reasonable way is to create extension of UIImage...在我看来,合理的方法是创建 UIImage 的扩展......

This is the code i found...这是我找到的代码...

public typealias SimpleClosure = (() -> ())
private var tappableKey : UInt8 = 0 
private var actionKey : UInt8 = 1 

extension UIImageView {
    
    @objc var callback: SimpleClosure {
        get {
            return objc_getAssociatedObject(self, &actionKey) as! SimpleClosure
        }
        set {
            objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    var gesture: UITapGestureRecognizer {
        get {
            return UITapGestureRecognizer(target: self, action: #selector(tapped))
        }
    }
    
    var tappable: Bool! {
        get {
            return objc_getAssociatedObject(self, &tappableKey) as? Bool
        }
        set(newValue) {
            objc_setAssociatedObject(self, &tappableKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            self.addTapGesture()
        }
    }

    fileprivate func addTapGesture() {
        if (self.tappable) {
            self.gesture.numberOfTapsRequired = 1
            self.isUserInteractionEnabled = true
            self.addGestureRecognizer(gesture)
        }
    }

    @objc private func tapped() {
        callback()
    }
}

and usage should look like用法应该是这样的

    @IBOutlet weak var exampleImageView: UIImageView! {
    didSet {
        self.exampleImageView.tappable = true
    }
}override func viewDidLoad() {
    super.viewDidLoad()
    self.exampleImageView.callback = {
         //TODO: Here you put the On click code.
    }
}

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

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