如何在故事板上制作UIImageView可点击(快速)

pjt*_*t11 29 uiimageview ios swift

我是swift的新手(以及一般的Xcode开发),我想知道如何在故事板上制作一个可点击的ImageView.我正在尝试做的是,当它点击它时,它显示另一个视图控制器.

Dha*_*esh 61

您可以为此添加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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是一种可能性,但使用图像创建"UIButton"要比使图像可点击更好.添加辅助功能选项时,您会感谢我. (7认同)

xxt*_*axx 23

您可以更轻松地完成这项工作,并通过Storyboard使图像可以点击,而无需编码.

  • 首先,您需要将其UITapGestureRecognizer拖到UIImageView故事板中.
  • 然后,您创建要在代码中运行的IBAction @IBAction func imageClicked(_ sender: Any) {}
  • 接下来,您需要通过选择手势识别器连接UITapGestureRecognizerIBAction您的班级Document Outline,然后切换到Connection Inspector Tab并拖动Sent Actions- > Selector到您的UIViewController位置,然后选择您之前创建的相应操作.
  • 最后,您必须User Interaction Enabled在图像视图上设置复选框.

完成,一个完全可点击的UIImageView,无需编写一行代码,除了您要调用的明显函数.但是,嘿,如果你想要推动一个segue,那么你可以通过使用手势识别器Triggered Segues而不是它来完全没有编码Sent Actions.

尽管Storyboard有其局限性,但无需为可点击图像编写代码.;)

在此输入图像描述

  • 即使我在 Identity Inspector 中选中了“User Interaction Enabled”,我也必须在“viewDidLoad()”中显式设置:“fooImage.isUserInteractionEnabled = true”才能使其正常工作(Xcode bug?还是什么?我不知道) (2认同)
  • @HassanTareq 请在身份检查器和属性检查器上设置“用户交互启用”;对我有用。 (2认同)

Zol*_*oor 5

我建议创建一个没有文本的UIButton,使其成为所需的图像。完成此操作后,您可以从图像中CTRL-Drag拖动到您要锁定的视图控制器。或者,您可以只在视图控制器的代码中进行手动选择的IBAction。