简体   繁体   中英

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, but 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:

  1. You must directly create a UIControl which is a UIView subclass, this class have the same behavior of a view but you can use the selector addTarget:action:forControlEvents: to control its events, or...
  2. You should use UIGestureRecognizer to control the interaction with your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM