如何使故事板上的 UIImageView 可点击 (swift)

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

我是 swift(以及 Xcode 开发的新手),我想知道如何使故事板上的 ImageView 可点击。我想要做的是让它在单击时显示另一个视图控制器。

我建议创建一个没有文本的 UIButton 并将其设为您想要的图像。这样做之后,您可以按住 CTRL 键并从图像拖动到您想要切换到的视图控制器。或者你可以在你的视图控制器的代码中创建一个 IBAction 来手动 segues。

在storyboard上设置image view user interaction enabled然后用这个方法获取

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

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

您可以为此添加 tapGesture。这是代码:

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

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

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

        }
    }
}

对于 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")
}

您可以做到甚至更容易并通过 Storyboard 使图像可点击,完全无需编码

  • 首先,您需要将 UITapGestureRecognizer 拖到 Storyboard 中的 UIImageView 上。
  • 然后您使用 @IBAction func imageClicked(_ sender: Any) {}
  • 在您的代码中创建您想要 运行 的 IBAction
  • 接下来您需要通过 selecting Document Outline 中的手势识别器将 UITapGestureRecognizer 连接到 class 中的 IBAction,然后切换到 Connection Inspector Tab 并将 Sent Actions -> Selector 拖到 UIViewController 然后 select 您之前创建的适当操作。
  • 最后,您必须在身份检查器和属性检查器的图像视图上设置复选框 User Interaction Enabled

完成,一个完全可点击的 UIImageView,除了您要调用的明显功能外,无需编写任何代码。但是,嘿,例如,如果你想改为推送一个 segue,那么你可以通过使用手势识别器 Triggered Segues 而不是它的 Sent Actions.

来完全不用编码。

虽然 Storyboard 有其局限性,但无需为可点击的图像编写代码。 ;)

我通过设置用户交互实现了这一点 enable = true

下面的代码在 TouchesBegan 中...干净简单

ImageView 也在 StackView 中

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

好吧,虽然你可以像上面提到的那样使用 UITapGestureRecognizer,但是如果你需要做一个快速的项目并且只关心应用程序的功能,最简单的方法是用一个透明的按钮覆盖你的 UIImageView 而没有文本,然后用它来编写你想要的任何代码。当然,如果您正在制作一个非常重要的项目或其他东西,则不推荐使用此方法,但如果您只想制作一个快速应用程序(假设是一些会议的非常简单的 MVP),此方法应该可以正常工作。

首先,创建一个图像视图。比写这段代码覆盖 func viewDidLoad() { super.viewDidLoad()

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

在你的视图控制器中。

UITapGestureRecognizer 方法做的一切都是可点击的

在我看来,合理的方法是创建 UIImage 的扩展...

这是我找到的代码...

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()
    }
}

用法应该类似于

    @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.
    }
}