【问题标题】:Swift Generic UIView subclass with protocol issue带有协议问题的 Swift Generic UIView 子类
【发布时间】:2015-02-01 02:41:45
【问题描述】:

我已扩展 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()

【问题讨论】:

    标签: ios generics swift uiview uigesturerecognizer


    【解决方案1】:

    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 也符合它。

    【讨论】:

    • 请检查我的更新 cmets,如果这是我可以做我需要的唯一方法,那么我会接受这个作为答案
    • (stackoverflow.com/questions/28262520/…) 这才是我真正想要解决的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多