Set custom class of UIView programmatically?
I am adding a UIView programmatically to superview, and i would like to add a target to the UIView to be able to perform any actions on touch. In order to add a target i need to set the custom class of the UIView to UIControl. Normally thats done in IB, but since im doing it programmatically i can't set it up that way. I tried to set UIControl like this, b开发者_如何学Cut its not working.
subView.class = UIControl;
Whats the proper way of doing that?
An instance of UIView does not have a target. If you want a target/action mechanism, create an instance of UIControl. Otherwise, use a gesture recognizer on your view.
The reason you sometimes set the class of a UIView to something else, say MyView, in IB is that you want to create a MyView, but IB doesn't have MyView in its library so you can't just drag one into your view. So, you drag in a UIView instead and change its class to MyView.
That's not necessary at all when you're instantiating an object in code rather than loading it from a .xib. In code, you know what class you want to instantiate, so you just instantiate that class:
MyView *subview = [[MyView alloc] initWithFrame:someFrame];
If you want subview to be a UIButton, you instantiate that instead:
UIButton *subview = [UIButton buttonWithType:UIButtonTypeRoundedRect];
Don't mess around with isa-swizzling, at least not now. If you're asking this question (and there's nothing wrong with asking this question) you should treat swizzling as a dark art that you might get to at some point in the future.
You have two options:
- You must directly create a
UIControl
which is aUIView
subclass, this class have the same behavior of a view but you can use the selectoraddTarget:action:forControlEvents:
to control its events, or... - You should use
UIGestureRecognizer
to control the interaction with your view.
精彩评论