Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: Override UIButton buttonWithType to return subclass

I want to be able to create a UIButton with an oversized responsive area. I know that one way to do that is to override the hitTest method in a subclass, but how do I instantiate my custom button object in the first place?

[OversizedButton buttonWithType: UIButtonTypeDetailDisclosure];

doesn't work out of the box because buttonWithType returns a UIButton, not an OversizedButton.

So it seems like I need to override the buttonWithType method as well. Does anyone know how to do this?

@implementation OversizedButton

+ (id)buttonWithType:(UIButtonType)buttonType
{
   // Construct and return an OversizedButton rather than a UIButton
   // Needs to handle special types such as UIButtonTypeDetailDisclosure
   // I NEED TO KNOW HOW TO DO THIS PART
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event 
{
   // Return results if touch event was in oversized region
   // I ALREADY KNOW HOW TO DO THIS PART
}

@end

Alternatively, maybe I could create the button using alloc/initWithFrame. But the buttonType property is readonly, so how do you create the custom button types?

Note: I know there are other ways to do this, such as having an invisible button behind the visible one. I don't care for that approach and would prefer to avoid it. Any help on the approach described above would be very helpful. Thanks

like image 921
Amagrammer Avatar asked Apr 01 '10 18:04

Amagrammer


2 Answers

UIButton buttonWithType: returns a UIButton or a UIRoundedRectButton, depending on the value of the type parameter.

As UIButton doesn't provide an initWithType: method, I believe it would be dangerous to try and override buttonWithType:.

I suggest you subclass UIControl instead. You can then add a button as a subview to your control, and intercept hitTest:withEvent:.

like image 151
Can Berk Güder Avatar answered Sep 16 '22 15:09

Can Berk Güder


Here's how I do it:

+ (instancetype)customButtonWithCustomArgument:(id)customValue {
    XYZCustomButtom *customButton = [super buttonWithType:UIButtonTypeSystem];
    customButton.customProperty = customValue;
    [customButton customFunctionality];
    return customButton;
}

Works also with other types, UIButtonTypeSystem is just an example.

like image 29
Rudolf Adamkovič Avatar answered Sep 16 '22 15:09

Rudolf Adamkovič