override func viewDidLoad() {
super.viewDidLoad()
buttonArray = [button1,button2,button3,button4,button5]
if buttonArray != nil{
for button in buttonArray!{
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(sender:)))
lpgr.minimumPressDuration = 1.5
button.addGestureRecognizer(lpgr)
}
}
// Do any additional setup after loading the view, typically from a nib.
}
func longPress(sender:UILongPressGestureRecognizer){
if sender.state == .began{
print("Button:\(sender.view?.tag)")
}
}
// 先判斷 buttonArray有值
if buttonArray != nil{
// buttonArray! -> 強制把optional 轉成 非 optional
// 新增一個 UILongPressGestureRecognizer()的物件, 放在變數 lpgr
// 設定 minimumPressDuration
// 然後加到button button.addGestureRecognizer(lpgr)
for button in buttonArray!{
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(sender:)))
lpgr.minimumPressDuration = 1.5
button.addGestureRecognizer(lpgr)
}
// #selector(ViewController.longPress(sender:))
// 這裡是指目前這個Viewcontroller 裡面的 longpress function
func longPress(sender:UILongPressGestureRecognizer){
if sender.state == .began{
print("Button:\(sender.view?.tag)")
}
}
// 判斷 sender的state 為 .began...
// 還可以取用 sender.view?.tag
這個tag 可以利用 story.board 去設定 tag
沒有留言:
張貼留言