制作我自己的UIControlEvent,并触发它?
我在视图控制器中创建了一个自定义的 UIView 类。我想让这个类可重用,所以不想将其构建为仅与这 1 个视图控制器一起使用。因此,我认为告诉视图控制器用户已与该类交互的最佳方式是以某种方式创建我自己的 UIControlEvent。也许是这样的:
[customClass addTarget:self action:@selector(whatIWantToHappen) forControlEvents:UIControlEventWhatever];
我对此不太了解,对此有什么建议吗?
I have a custom class of a UIView I've made inside my viewcontroller. I want to make this class re-usable and so don't want to build it to work just with this 1 viewcontroller. Because of this, I think the best way of telling my viewcontroller that the user has interacted with the class is to somehow make my own UIControlEvent. Maybe something like:
[customClass addTarget:self action:@selector(whatIWantToHappen) forControlEvents:UIControlEventWhatever];
I don't know much about doing this though, any suggestions on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过子类化
UIControl
来实现此目的,它继承自 UIView,但提供了一些用于处理目标和操作的附加方法。看看 常量,也许预定义的控制事件之一已经符合您的要求。否则,您可以在UIControlEventApplicationReserved
提供的范围内定义自己的事件,但是您应该永远为您自己的事件添加UI...
前缀,该“命名空间”是为 UIKit 保留的。You could do this by subclassing
UIControl
, which inherits from UIView, but provides some additional methods for handling targets and actions. Have a look at the constants, perhaps one of the predefined control events already fits your bill. Otherwise, you could define your own events in the range provided byUIControlEventApplicationReserved
, you should however never prefix your own things withUI...
, that 'namespace' is reserved for UIKit.除了 omz 的答案之外,执行此操作时您可能会收到编译器警告:
编译器不喜欢最后一个参数使用的自定义值,其类型为
UIControlEvents
,因此它会抛出一个警告。我这样做了:
看哪!不再有警告。
我在 this StackOverflow 答案中找到了这个符号。
注意:对于
UIControlEvents
,我强烈避免使用任何不可用的值,因此我仅使用UIControlEventApplicationReserved
值。此外,typedef 不再需要每次都键入“enum”,并且已成为惯例。
In addition to the answer by omz, you may get a compiler warning when doing this:
The compiler doesn't like the custom value being used for the last parameter, which is of type
UIControlEvents
, so it throws a warning.I did this:
Behold! No more warnings.
I found this notation in this StackOverflow answer.
N.B. For
UIControlEvents
, I am strongly avoiding the use of any unavailable values, so I only use theUIControlEventApplicationReserved
value.Additionally, the typedef relinquishes the need to type 'enum' every time and is customary.