我希望能够创建一个具有超大响应区域的 UIButton.我知道这样做的一种方法是覆盖子类中的 hitTest 方法,但我如何首先实例化我的自定义按钮对象?
[OversizedButton buttonWithType: UIButtonTypeDetailDisclosure];
无法开箱即用,因为 buttonWithType 返回的是 UIButton,而不是 OversizedButton.
看来我也需要重写 buttonWithType 方法.有谁知道怎么做?
@implementation OversizedButton+ (id)buttonWithType:(UIButtonType)buttonType{//构造并返回一个 OversizedButton 而不是 UIButton//需要处理 UIButtonTypeDetailDisclosure 等特殊类型//我需要知道如何做这部分}- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{//如果触摸事件在超大区域,则返回结果//我已经知道如何做这部分}@结尾
或者,也许我可以使用 alloc/initWithFrame 创建按钮.但是 buttonType 属性是只读的,那么如何创建自定义按钮类型呢?
注意:我知道还有其他方法可以做到这一点,例如在可见按钮后面设置一个不可见按钮.我不喜欢这种方法,宁愿避免它.对上述方法的任何帮助都会非常有帮助.谢谢
UIButton buttonWithType:
返回 UIButton
或 UIRoundedRectButton
,具体取决于type
参数的值.
由于 UIButton
没有提供 initWithType:
方法,我认为尝试重写 buttonWithType:
会很危险.p>
我建议您改为子类 UIControl
.然后,您可以将按钮作为子视图添加到您的控件,并拦截 hitTest:withEvent:
.
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
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:
.
这篇关于iPhone:覆盖 UIButton buttonWithType 以返回子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!