Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The simplest approach that I often use is to extend UIControl, but to make use of the inherited addTarget method to receive callbacks for the various events. The key is to listen for both the sender and the event so that you can find out more information about the actual event (such as the location of where the event occurred).</p> <p>So, just simply subclass UIControl and then in the init method (make sure your initWithCoder is also setup if you are using nibs) , add the following:</p> <pre><code>[self addTarget:self action:@selector(buttonPressed:forEvent:) forControlEvents:UIControlEventTouchUpInside]; </code></pre> <p>Of course, you can choose any of the standard control events including UIControlEventAllTouchEvents. Notice that the selector will get passed two objects. The first is the control. The second is the info about the event. Here's an example of using the touch event to toggle a button depending on if the user pressed on the left and right.</p> <pre><code>- (IBAction)buttonPressed:(id)sender forEvent:(UIEvent *)event { if (sender == self.someControl) { UITouch* touch = [[event allTouches] anyObject]; CGPoint p = [touch locationInView:self.someControl]; if (p.x &lt; self. someControl.frame.size.width / 2.0) { // left side touch } else { // right side touch } } } </code></pre> <p>Granted, this is for pretty simplistic controls and you may reach a point where this will not give you enough functionality, but this has worked for all my purposes for custom controls to this point and is really easy to use since I typically care about the same control events that the UIControl already supports (touch up, drag, etc...)</p> <p>Code sample of custom control here: <a href="http://www.homick.com/posts/custom-uiswitch-control" rel="noreferrer">Custom UISwitch</a> (note: this does not register with the buttonPressed:forEvent: selector, but you can figure that out from the code above)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload