Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Generic UIView subclass with protocol issue

I have extended UIView to conform UIGestureRecognizerDelegate protocol

The below code compiles

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

Now I am trying to create a Generic Subclass to create different UIView subclass's

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
    }
}

The strange thing to me is, T.addGestureRecognizer expects UIView rather than UIGestureRecognizer

Update:

I want the return type of MyView to be subclass of UIView,

let view = MyView<UIView>()

// I want to use it this way

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

// But, I have to use this way

view.subview.tintColor = UIColor.redColor()
like image 812
RK1979 Avatar asked Oct 20 '22 18:10

RK1979


1 Answers

T is the type of your subview. You must create an instance of it to call addGestureRecognizer and to set it as a delegate of a gesture recognizer.

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)
    }
}

Note that you're assuming that the class passed to create a MyView instance has a method named tapGestureHandler:. You should probably add this method to a protocol and make T conform to it too.

like image 80
Marcelo Fabri Avatar answered Oct 22 '22 23:10

Marcelo Fabri