iPhone: Override UIButton buttonWithType to return subclass

梦想与她 提交于 2020-01-11 08:17:26

问题


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


回答1:


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:.




回答2:


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.




回答3:


The buttonType property is not used anywhere in UIKit, and in your code you could always check -isKindOfClass:, so overwriting +buttonWithType: for this property is rather pointless IMO. Just use

return [[[OversizedButton alloc] initWithFrame:...] autorelease];

(You can override the button type with the undocumented method _setButtonType:.)



来源:https://stackoverflow.com/questions/2562713/iphone-override-uibutton-buttonwithtype-to-return-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!