如何为单击图像时添加动作?

时间:2019-01-30 15:03:52

标签: ios swift button action

我正在尝试将自定义图片用作应用中的按钮。如何为图片添加操作?

这是针对iOS应用的,我不想将默认的文本按钮用作按钮。我已经尝试过Control +将图片拖到ViewController中,但是没有“ Action”选项。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let designChoice = designPrac.randomElement()
    let forChoice = forWhatPrac.randomElement()
    let helpChoice = toHelpPrac.randomElement()

    designLabel.text = designChoice
    forLabel.text = forChoice
    helpLabel.text = helpChoice
}

这是我在应用启动时必须运行的代码,但是当我单击图像按钮时,我找不到使它正常工作的方法。

3 个答案:

答案 0 :(得分:0)

要将动作添加到UIImageView,您需要向其添加UITapGestureRecognizer,您可以这样做:

<#YourImageView#>.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleImageTap)))

然后您可以使用选择器来处理水龙头:

@objc func handleImageTap() {
    // handle image tap here    
}

答案 1 :(得分:0)

您可以为此目的使用addGestureRecognizer:

let imageView = UIImageView()
//add necessary code 
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MethodForAction)))

答案 2 :(得分:-1)

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

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

    }
}
相关问题