ios - 我在 MonoTouch 中对 UIButton 进行了子类化,但底层 ObjC 类仍然是 UIButton

标签 ios uiview xamarin.ios uikit

我有继承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) { }
}

如果我在另一个 View 的 xib 中使用 BackButton,其底层类将被视为 BackButton:

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

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

有什么问题吗?

最佳答案

事实证明,我必须调用无参数 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:] 无法了解我的自定义 View ,因此它只会创建一个 UIButton

关于ios - 我在 MonoTouch 中对 UIButton 进行了子类化,但底层 ObjC 类仍然是 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949554/

相关文章:

windows - 是否可以在 Visual Studio 中构建 Monotouch 应用程序?

ios - 如何从 UINavigationBar 中删除背景图像

ios - 多个带有刷新控件的UITableViewBugs

ios - 更新 tableview 中的单元格同时更新另一个单元格

ios - WKWebView 显示白屏,使用 native <->webview 通信

ios - 很难将 UIView 添加到 UIViewController 作为 subview

ios - UICollectionView Xamarin.iOS,带按钮的自定义单元格

ios - Quick Action (3D Touch) 后的启动周期

ios - 并排排列 3 个 UIButtons(等宽)

ios - 在 UITableViewCell 内动画 UILabel 文本更改