iOS/Swift 无法向子类添加手势

标签 ios swift gesture

我正在编写一个子类,但无法为其添加手势识别。 选择器错误。这是我的代码:

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/

相关文章:

ios - 本地图移动时执行操作

ios - Facebook 好友的 ID 无效

Swift:标签文本 --> "fatal error: unexpectedly found nil while unwrapping an Optional value"

iOS TapGestureRecognizer 为 numberOfTapsRequired=1 吃双击

ios - 如何使用手势 swift iOS 转换到 View Controller

iphone - run loop/drawRect 中神秘的 "progressive slowing"问题

ios - 如何更改 UINavigationController Title & backButton 编程?

android - 使用超声波确定 2 个移动设备的相对位置

android - 在我在 android 中触摸的点上的 GestureOverlayView 中添加一个 child ?

android - 在后台监听触摸事件