我所要做的就是在我长时间触摸(UILongPressGestureRecognizer)时调用当前上下文中的新控制器。 代码如下:
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!{
didSet{
button.addGestureRecognizer(UILongPressGestureRecognizer(target: self,
action: #selector(settingTheButton(_:))))
}
}
func settingTheButton(_ recognizer: UILongPressGestureRecognizer){
print("touchTheColorButton was called") // here the method invokes twice
if let button = recognizer.view as? UIButton{
performSegue(withIdentifier: "setTheButtonColor", sender: button)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.identifier == "setTheButtonColor", let vc = segue.destination as? SettingsForButtonVC, let senderButton = sender as? UIButton {
vc.button = senderButton
}
}
}
我不明白。为什么方法settingTheButton被调用两次?它不会干扰或伤害程序,但它真的打扰了我。
控制台: touchTheColorButton被召唤 touchTheColorButton被召唤 2017-02-18 01:28:12.499552测试[1042:223223]警告:尝试出示已经呈现的内容
答案 0 :(得分:2)
你的问题是你没有听到手势的状态。
更改为:
func settingTheButton(_ recognizer: UILongPressGestureRecognizer){
guard recognizer.state == .ended else { return }
print("touchTheColorButton was called") // here the method invokes twice
if let button = recognizer.view as? UIButton{
performSegue(withIdentifier: "setTheButtonColor", sender: button)
}
}
我没有正确测试。如果在downvoting之前它没有工作,请告诉我。
答案 1 :(得分:1)
扩展@Marco Santarossa提供的解决方案(无法发表评论)。这将正常工作:
func settingTheButton(_ recognizer: UILongPressGestureRecognizer){
// Get the button just as you have done
if let button = recognizer.view as? UIButton{
// Take only the `.ended` event, discarding any other ones
if recognizer.state == .ended {
performSegue(withIdentifier: "setTheButtonColor", sender: button)
}
}
}
您的代码存在的问题是settingTheButton(_ recognizer:)
每次在UILongPressGestureRecognizer
触发事件时都会调用.began
,而不仅仅是在释放按钮时,这是您可能期望的行为。这两个事件是.ended
(一旦新闻被认为是长按)和.ended
(在释放长按后)。
简单地忽略两者将使您的代码只被调用一次,另外它在.ended
上更有意义,因为您可能希望在释放按钮后而不是在按钮期间出现新屏幕按
注意:你知道,最好只允许.changed
,因为除了我知道的那两个之外,至少有一个其他常见事件可以被触发。如果您使用的是强力触控设备,create table LSNBoundaries (LSN binary(10) not null, IsProcessingComplete bit not null);
会被多次调用,每次轻微的压力变化都会被调用一次。