我有一个视图和 view.UserInteractionenabled = no,添加了一个按钮到视图中。我只需要点击这个按钮,是否有可能只为按钮启用交互。
我有一个视图和 view.UserInteractionenabled = no,添加了一个按钮到视图中。我只需要点击这个按钮,是否有可能只为按钮启用交互。
除非对于视图和其所有父视图都设置了userInteractionEnabled
为YES
,否则该视图无法接收触摸事件,直到达到UIWindow
对象。
您可以创建一个UIView
的子类来包含按钮,并通过重写hitTest:withEvent:
方法使其忽略按钮外部的触摸事件。 例如:
@interface MyView : UIView
@property (nonatomic, strong) IBOutlet UIButton *button;
@end
@implementation MyView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *subview = [super hitTest:point withEvent:event];
return subview == self.button ? subview : nil;
}
@end