【问题标题】:I subclassed UIButton in MonoTouch but underlying ObjC class is still UIButton我在 MonoTouch 中将 UIButton 子类化,但底层 ObjC 类仍然是 UIButton
【发布时间】:2012-10-18 07:42:59
【问题描述】:

我有继承 UIButtonBackButton
它没有 xib,非常简单,并且包含一些我省略的布局逻辑。

我是这样声明的:

[Register("BackButton")]
public class BackButton : UIButton
{
    public BackButton (string text, EventHandler handler)
        : base (UIButtonType.Custom)
    {
        TouchUpInside += handler;
        SetTitle (text, UIControlState.Normal);
    }

    public BackButton(IntPtr handle) : base(handle) { }
}

如果我在另一个视图的 xib 中使用BackButton,它的底层类被视为BackButton

但是,当我从代码创建实例时,底层类只是 UIButton:

这很令人沮丧,因为我正在为这个类尝试use UIAppearance,我需要它是正确的实例。

有什么问题?

【问题讨论】:

    标签: ios uiview xamarin.ios uikit


    【解决方案1】:

    事实证明,我必须调用无参数的 UIButton 构造函数,而不是我正在调用的构造函数。
    从构造函数定义中删除 : base (UIButtonType.Custom) 就足以让它工作:

    public BackButton (string text, EventHandler handler)
         // : base (UIButtonType.Custom) -- remove this line
    {
        TouchUpInside += handler;
        SetTitle (text, UIControlState.Normal);
    }
    

    事后看来,这完全有道理,因为 MonoTouch 提供的 UIButton(UIButtonType) 构造函数实际上调用了 [UIButton buttonWithType:]

    public UIButton (UIButtonType type) : base (
        Messaging.IntPtr_objc_msgSend_int (UIButton.class_ptr,
            UIButton.selButtonWithType_, (int)type)
        ) { }
    

    我想,[UIButton buttonWithType:] 不可能知道我的自定义视图,所以它只会创建一个 UIButton

    【讨论】:

    • 漂亮,谢谢。我有一个按钮,其中 IntPtr 构造函数可以完美地工作,而当我使用 UIButtonType 从代码创建一个按钮时却没有。这很有意义,但在找到您的答案并获得“哈哈”时刻之前,我尝试了很多方法。
    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多