How to use a custom UIButton with Interface Builde

2019-06-21 06:05发布

问题:

I have a subclass UIButton that loads a Nib:

@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

And I can add this button to a view, like this:

// ViewController.m

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

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

[self.view addSubview:button];

My problem is I don't know how to do it from Interface Bulder, how to use this UIButton subclass instead of the normal one.

Already changed Button Type to Custom, and Custom Class to BlaButtonVC, but it's not enough. It'll call BlaButtonVC initWithFrame, but button will not appear nor in Interface Builder, nor in Simulator.

What did I missed?

Here you can find the full sample:
https://www.dropbox.com/s/ioucpb6jn6nr0hs/blabla1.zip

回答1:

When initialized from the StoryBoard, it calls the method initWithCoder: instead of initWithFrame:. Aside from that, everything is correct.



回答2:

In Interface Builder you can not add subviews to UIButton, so here are some ideas:

  1. Do it in code.
  2. Place the button below the labels and image, so it would receive touches and work as expected.
  3. Use UITableView with cells (this looks like what you are trying to achieve).
  4. Use custom UIView with UITapGestureRecognizer.