Swift Generic UIView with protocol

I added a UIView to comply with the UIGestureRecognizerDelegate protocol

The following code compiles

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

Now I'm trying to create a general subclass to create another subclass of 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 } } 

Strange thing for me: T.addGestureRecognizer expects a UIView, not a UIGestureRecognizer

Update

I want the return type MyView to be a 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 method

 view.subview.tintColor = UIColor.redColor() 
+5
source share
1 answer

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

 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 believe that the class passed to instantiate MyView has a method called tapGestureHandler: You should probably add this method to the protocol and make T conform to it.

+3
source

Source: https://habr.com/ru/post/1212353/


All Articles