我正在编写一个子类,但无法为其添加手势识别。 选择器错误。这是我的代码:
import UIKit
class Alert: KeyboardViewController {
var AlertContainer = UIView()
func ShowAlert(message: String,view: UIView)
{
var tap = UITapGestureRecognizer(target: self, action:Selector("CloseAlertView"))
tap.numberOfTapsRequired = 1
AlertContainer.addGestureRecognizer(tap)
AlertContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
AlertContainer.userInteractionEnabled = true
AlertContainer.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.8)
view.addSubview(AlertContainer)
var CTop = NSLayoutConstraint(item: AlertContainer, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0)
var CRight = NSLayoutConstraint(item: AlertContainer, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0)
var CLeft = NSLayoutConstraint(item: AlertContainer, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0)
var CBottom = NSLayoutConstraint(item: AlertContainer, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
view.addConstraints([CTop,CRight,CLeft,CBottom])
}
func CloseAlertView() {
AlertContainer.removeFromSuperview()
}
}
但是当我点击此 View 时,出现错误:exc_bad_access 或某个时间无法识别的选择器发送到实例。真的不知道为什么? 还有一个问题是我无法通过 super.view 访问父类 View ?
最佳答案
你是不是在用下面的方式调用这个类(如果不是忽略我的回答)?
// wrong implementation
func myFunc() {
var a = Alert()
a.ShowAlert("Message", view: view)
}
前面的代码是错误的(并导致 BAD_ACCESS),因为函数完成后 a
不再存在。因此,当手势被触发时,它什么都不做并崩溃。
解决方案:
var a = Alert() // a property of the caller class
func myFunc() {
a.ShowAlert("Message", view: view)
}
通过这种方式,a
的生命周期足够长,可以等待手势。
关于iOS/Swift 无法向子类添加手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27112130/