在UIView中触摸后发出警报

时间:2017-06-26 15:17:08

标签: ios swift uiview

我有UIViewUILabel。现在我想在点击UIView时添加提醒。是否可以在视图上单击事件?

这是我未完成的代码:

class viewController: UIViewController {


@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBOutlet weak var view3: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
}

func action(_ sender: UIView) {
    // Create the alert controller
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)

    // Create the actions
    let okAction = UIAlertAction(title: "title", style: UIAlertActionStyle.default) {
    }

    // Add the actions
    alertController.addAction(okAction)

    // Present the controller
    self.present(alertController, animated: true, completion: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
} 
}

函数action应该看起来像我的例子。现在我需要知道如何调用它并将其引用到UIView

2 个答案:

答案 0 :(得分:1)

是。在viewDidLoae中,添加一个静音中心

let gesture = UITapGestureRecognizer(target: self, action:  #selector (viewClicker(sender:)))
self.view1.addGestureRecognizer(gesture)

然后在此功能中捕捉您的点击操作

func viewClicker(sender : UITapGestureRecognizer) {
    // Do what you want
}

答案 1 :(得分:1)

单击特定控件时,只需覆盖 touchesBegan 方法即可。您可以直接比较UIView

,而不是检查标签
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        switch touch.view? {
           case self.view1:
                      // show alert
                       break
           case self.view2:
                      // show alert
                       break
           case self.view3:
                      // show alert
                       break
           default:
                   break
        }

    }
}