How to correctly subclass UIControl?

HelloMoon picture HelloMoon · Aug 7, 2009 · Viewed 43.4k times · Source

I don't want UIButton or anything like that. I want to subclass UIControl directly and make my own, very special control.

But for some reason, none of any methods I override get ever called. The target-action stuff works, and the targets receive appropriate action messages. However, inside my UIControl subclass I have to catch touch coordinates, and the only way to do so seems to be overriding these guys:

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    NSLog(@"begin touch track");
    return YES;
}

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    NSLog(@"continue touch track");
    return YES;
}

They get never called, even though the UIControl is instantiated with the designates initializer from UIView, initWithFrame:.

All examples I can find always use a UIButton or UISlider as base for subclassing, but I want to go closer to UIControl since that's the source for what I want: Fast and undelayed Touch coordinates.

Answer

pixelfreak picture pixelfreak · Sep 25, 2011

I know this question is ancient, but I had the same problem and I thought I should give my 2 cents.

If your control has any subviews at all, beginTrackingWithTouch, touchesBegan, etc might not get called because those subviews are swallowing the touch events.

If you don't want those subviews to handle touches, you can set userInteractionEnabled to NO, so the subviews simply passes the event through. Then you can override touchesBegan/touchesEnded and manage all your touches there.

Hope this helps.