iPhone:覆盖UIButton buttonWithType以返回子类 [英] iPhone: Override UIButton buttonWithType to return subclass

查看:90
本文介绍了iPhone:覆盖UIButton buttonWithType以返回子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建一个具有超大响应区域的UIButton。我知道一种方法是覆盖子类中的hitTest方法,但是如何在第一时间实例化我的自定义按钮对象?

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];

开箱即用,因为buttonWithType返回的是UIButton,而不是OversizedButton。

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

因此我似乎也需要覆盖buttonWithType方法。有谁知道怎么做?

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

或者,也许我可以使用alloc / initWithFrame创建按钮。但是buttonType属性是readonly,那么如何创建自定义按钮类型?

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:返回 UIButton UIRoundedRectButton ,具体取决于类型参数的值。

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

As UIButton 不提供 initWithType:方法,I相信尝试覆盖 buttonWithType:会很危险。

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

我建议你继承取而代之的是UIControl 。然后,您可以将一个按钮作为子视图添加到控件中,并拦截 hitTest:withEvent:

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以返回子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆