【问题标题】:How to use a custom UIButton with Interface Builder?如何在 Interface Builder 中使用自定义 UIButton?
【发布时间】:2012-12-09 09:28:57
【问题描述】:

我有一个加载 Nib 的子类 UIButton:

@implementation BlaButtonVC

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSArray *subViews = [[NSBundle mainBundle] loadNibNamed:@"BlaButton" owner:self options:nil];
        [self addSubview:subViews[0]];
    }
    return self;
}

@end

我可以将此按钮添加到视图中,如下所示:

// ViewController.m

BlaButtonVC *button = [[BlaButtonVC alloc] initWithFrame:CGRectMake(10, 10, 280, 44)];

button.titleXLabel.text = @"Nyuff";
button.descLabel.text = @"Kukk";

[self.view addSubview:button];

我的问题是我不知道如何从 Interface Bulder 做到这一点,如何使用这个 UIButton 子类而不是普通的子类。

已经将按钮类型更改为自定义,自定义类更改为 BlaButtonVC,但这还不够。它会调用 BlaButtonVC initWithFrame,但按钮不会出现在 Interface Builder 中,也不会出现在 Simulator 中。

我错过了什么?

您可以在此处找到完整示例:
https://www.dropbox.com/s/ioucpb6jn6nr0hs/blabla1.zip

【问题讨论】:

    标签: ios xcode uibutton interface-builder custom-controls


    【解决方案1】:

    StoryBoard 初始化时,它调用方法initWithCoder: 而不是initWithFrame:。除此之外,一切都是正确的。

    【讨论】:

    • 是的,它调用-initWithCoder:,但你不应该覆盖它。相反,您应该覆盖-awakeFromNib,因为此时一切都已设置好。 (甚至不要考虑自己打电话给这两个。)
    • 覆盖initWithCoder:awakeFromNib 没有任何问题。这取决于他希望如何设置。
    • 在大多数(如果不是全部)情况下,-awakeFromNib 最好覆盖。请参阅-[NSObject(UINibLoadingAdditions) awakeFromNib] 的文档。
    【解决方案2】:

    在 Interface Builder 中,您不能将子视图添加到 UIButton,所以这里有一些想法:

    1. 在代码中实现。
    2. 将按钮放在标签和图像下方,这样它就可以接收触摸并按预期工作。
    3. UITableView 与单元格一起使用(这看起来就像您要实现的目标)。
    4. 使用自定义UIViewUITapGestureRecognizer

    【讨论】:

    • @Julian 你在我的回答中看到了“not”这个词吗?这是第 6 次。无论如何,在 3 年后查看问题和我的答案,它们对我来说毫无意义。
    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多