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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With