以编程方式设置 UIView 的自定义类?
我以编程方式将 UIView 添加到超级视图,并且我想向 UIView 添加一个目标,以便能够在触摸时执行任何操作。为了添加目标,我需要将 UIView 的自定义类设置为 UIControl。通常这是在 IB 中完成的,但由于我是以编程方式进行的,所以我无法以这种方式进行设置。我尝试像这样设置 UIControl,但它不起作用。
subView.class = UIControl;
这样做的正确方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
UIView 的实例没有目标。如果您需要目标/操作机制,请创建 UIControl 的实例。否则,请使用手势识别器根据你的观点。
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.
有时,在 IB 中将 UIView 的类设置为其他内容(例如 MyView)的原因是,您想要创建一个 MyView,但 IB 的库中没有 MyView,因此您不能将其拖到视图中。因此,您拖入一个 UIView 并将其类更改为 MyView。
当您在代码中实例化对象而不是从 .xib 加载它时,这根本没有必要。在代码中,您知道要实例化哪个类,因此您只需实例化该类:
如果您希望子视图成为 UIButton,则实例化它:
不要乱搞 isa-swizzling,至少现在不要。如果你问这个问题(问这个问题没有错),你应该将 swizzling 视为一门黑暗艺术,你可能会在未来的某个时候接触到它。
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:
If you want subview to be a UIButton, you instantiate that instead:
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.
您有两个选择:
UIControl
,它是UIView
子类,此类具有与视图相同的行为,但您可以使用选择器
addTarget:action:forControlEvents:
来控制其事件,或者...
UIGestureRecognizer
来控制与您的交互看法。
You have two options:
UIControl
which is aUIView
subclass, this class have the same behavior of a view but you can use theselector
addTarget:action:forControlEvents:
to control its events,or...
UIGestureRecognizer
to control the interaction with yourview.