0

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?

JonasG
  • 9,274
  • 12
  • 59
  • 88

3 Answers3

2

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.

Macmade
  • 52,708
  • 13
  • 106
  • 123
2

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.

Caleb
  • 124,013
  • 19
  • 183
  • 272
0

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.
specktro
  • 295
  • 1
  • 5
  • 12