Event Management in Custom UIControl

I subclass UIControl to create a custom control that contains various standard controls.

For this discussion, suppose my custom UIControl contains only UIButton.

What I would like to achieve is that clicking anywhere on a custom UIControl generates a click event for that custom UIControl. The standard behavior is that UIButton will process and consume (i.e. do not forward) the click event.

UIButton is not recommended as a subclass; I cannot find an easy way to achieve this.

Any suggestions?

+4
source share
4 answers

I came up with a simple solution that does not require a subclass of UIButton.

In the action method defined for the UIButton TouchUpInside control event, I added the following line of code:

[self sendActionsForControlEvents:UIControlEventTouchUpInside]; 

This causes the TouchUpInside control event to be called when clicked anywhere on a custom UIControl.

+12
source

UIButton is designed to handle touch events. You can set userInteractionEnabled to NO so that the button does not accept any touches, or you can use addTarget:action:forControlEvents: on the button to invoke a method call in your class when the button is clicked.

BTW, where is the UIButton subclassification discouraged?

0
source

Often, I find useful tasks related to user interaction in the UIResponder class , which is the superclass of UIControl - UIButton . Read about – touchesBegan:withEvent: – touchesMoved:withEvent: – touchesEnded:withEvent: – touchesCancelled:withEvent: at http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIResponder_Class/Reference /Reference.html . You can find ways to configure user interaction for your UIButton . By the way, I don’t think that there will be any problem of subclassing UIButton , regardless of what you heard, as long as your implementation is correctly added to the implementation of the superclass or even responsibly cancels it.

0
source

UIView has a method called -hitTest:withEvent: that the event system uses to traverse the view hierarchy and send events to sub-items. If you want the parent view to collect all events that might otherwise be sent to its subzones, simply override the parent -hitTest:withEvent: as follows:

 -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ if(CGRectContainsPoint([self bounds], point){ return self; } return [super hitTest:point withEvent:event]; } 
0
source

Source: https://habr.com/ru/post/1342418/


All Articles