【问题标题】:iPhone: Override UIButton buttonWithType to return subclassiPhone:覆盖 UIButton buttonWithType 以返回子类
【发布时间】:2023-03-28 00:56:01
【问题描述】:

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

[OversizedButton buttonWithType: UIButtonTypeDetailDisclosure];

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

看来我也需要重写 buttonWithType 方法。有谁知道怎么做?

@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 属性是只读的,那么如何创建自定义按钮类型呢?

注意:我知道还有其他方法可以做到这一点,例如在可见按钮后面设置一个不可见按钮。我不喜欢这种方法,宁愿避免它。对上述方法的任何帮助都会非常有帮助。谢谢

【问题讨论】:

    标签: iphone uibutton subclass


    【解决方案1】:

    UIButton buttonWithType: 返回 UIButtonUIRoundedRectButton,具体取决于 type 参数的值。

    由于UIButton 没有提供initWithType: 方法,我认为尝试覆盖buttonWithType: 会很危险。

    我建议你改为子类UIControl。然后,您可以将按钮作为子视图添加到您的控件,并拦截hitTest:withEvent:

    【讨论】:

    • 我正在尝试这个,因为它确实看起来另一个不实用。不过,这似乎非常不雅。谢谢。
    【解决方案2】:

    我是这样做的:

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

    也适用于其他类型,UIButtonTypeSystem 只是一个示例。

    【讨论】:

      【解决方案3】:

      buttonType 属性在 UIKit 中的任何地方都没有使用,并且在您的代码中您总是可以检查-isKindOfClass:,因此为该属性覆盖+buttonWithType: 是相当没有意义的 IMO。只需使用

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

      (您可以使用未记录的方法_setButtonType: 覆盖按钮类型。)

      【讨论】:

      • 您是否认真建议我在需要 Apple 批准的商业应用程序中使用未记录的方法?
      • @Ama:我建议你不要理会buttonType 属性。但如果必须,唯一的方法是通过未记录的方法进行更改。
      • 好吧,我需要显示 UIButtonTypeDetailDisclosure 按钮,所以“不打扰”是行不通的。我是否应该假设据您所知没有办法覆盖 buttonWithType 方法?谢谢
      猜你喜欢
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2015-12-26
      • 2012-01-17
      相关资源
      最近更新 更多