我是新手(通常是Xcode开发人员),我想知道如何使故事板上的ImageView可点击。我正在尝试做的是使它单击,从而显示另一个视图控制器。
您可以为此添加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 } } }
斯威夫特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 } } }
斯威夫特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 } } }