具有协议问题的Swift Generic UIView子类

时间:2015-02-01 02:41:46

标签: ios generics swift uiview uigesturerecognizer

我已扩展 UIView 以符合 UIGestureRecognizerDelegate 协议

以下代码编译

let label = UILabel()
let recognizer = UITapGestureRecognizer(target: label.self, action: Selector("tapGestureHandler:"))
recognizer.delegate = label.self
label.addGestureRecognizer(recognizer)

现在我正在尝试创建一个通用子类来创建不同的UIView子类

class MyView<T:UIView> {
    init() {
        (T.self as T.Type).init(frame: CGRectZero)
    }

    func addGestureToView() {
        let recognizer = UITapGestureRecognizer(target: T.self, action: Selector("tapGestureHandler:"))
        // The below two lines produces syntax error    
        recognizer.delegate = T.self // does not conform to protocol 'UIGestureRecognizerDelegate'
        T.addGestureRecognizer(recognizer) // UITapGestureRecognizer cannot convertible to UIView
    }
}

对我来说奇怪的是, T.addGestureRecognizer 期望UIView而不是 UIGestureRecognizer

更新

我希望MyView的返回类型是UIView的子类,

let view = MyView<UIView>()

//我想以这种方式使用它

view.tintColor = UIColor.redColor() // I can't

//但是,我必须这样使用

view.subview.tintColor = UIColor.redColor()

1 个答案:

答案 0 :(得分:3)

T是您的子视图的类型。您必须创建一个实例来调用addGestureRecognizer并将其设置为手势识别器的委托。

class MyView<T:UIView where T: UIGestureRecognizerDelegate> {
    var subview: T

    init() {
        subview = T(frame: CGRectZero)
    }

    func addGestureToView() {
        let recognizer = UITapGestureRecognizer(target: subview, action: Selector("tapGestureHandler:"))

        recognizer.delegate = subview
        subview.addGestureRecognizer(recognizer)
    }
}

请注意,您假设传递给创建MyView实例的类具有名为tapGestureHandler:的方法。您应该将此方法添加到协议中,并使T也符合它。