3 回答

TA貢獻1810條經(jīng)驗 獲得超5個贊
您可以通過創(chuàng)建UILongPressGestureRecognizer實例并將其附加到按鈕開始。
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[longPress release];
然后實現(xiàn)處理手勢的方法
- (void)longPress:(UILongPressGestureRecognizer*)gesture {
if ( gesture.state == UIGestureRecognizerStateEnded ) {
NSLog(@"Long Press");
}
}
現(xiàn)在,這將是基本方法。您還可以設(shè)置印刷機的最短持續(xù)時間以及允許的錯誤數(shù)量。還要注意的是,如果您在識別出手勢之后會多次調(diào)用該方法,那么如果您想在其結(jié)束時執(zhí)行某些操作,則必須檢查其狀態(tài)并進行處理。

TA貢獻1790條經(jīng)驗 獲得超9個贊
作為可接受答案的替代方法,可以使用Interface Builder在Xcode中非常輕松地完成此操作。
只需將“ 長按手勢識別器”從對象庫中拖放到想要長按動作的按鈕頂部即可。
接下來,將剛添加的“ 長按手勢識別器 ”中的“動作”連接到視圖控制器,選擇類型為“發(fā)件人”的發(fā)件人UILongPressGestureRecognizer。在IBAction使用該代碼的代碼中,該代碼與已接受答案中建議的代碼非常相似:
在Objective-C中:
if ( sender.state == UIGestureRecognizerStateEnded ) {
// Do your stuff here
}
或在Swift中:
if sender.state == .Ended {
// Do your stuff here
}
但我必須承認,嘗試后,我更喜歡@shengbinmeng提出的建議,以作為已接受答案的注釋,該建議使用:
在Objective-C中:
if ( sender.state == UIGestureRecognizerStateBegan ) {
// Do your stuff here
}
或在Swift中:
if sender.state == .Began {
// Do your stuff here
}
區(qū)別在于,使用Ended,您可以在抬起手指時看到長按的效果。使用Began,您會在系統(tǒng)抓住長按后立即看到長按的效果,甚至在將手指從屏幕上抬起之前也是如此。

TA貢獻1799條經(jīng)驗 獲得超6個贊
接受答案的Swift版本
我對using進行了其他修改,UIGestureRecognizerState.Began而不是.Ended因為這可能是大多數(shù)用戶自然希望的。嘗試一下它們,然后自己看看。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// add gesture recognizer
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
self.button.addGestureRecognizer(longPress)
}
func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}
@IBAction func normalButtonTap(sender: UIButton) {
print("Button tapped")
}
}
- 3 回答
- 0 關(guān)注
- 1110 瀏覽
添加回答
舉報