create uibutton subclass

前端 未结 5 1716
说谎
说谎 2020-11-28 14:10

I tried to subclass UIButton to include an activity indicator, but when i use initWithFrame:(since i\'m subclassing uibutton i\'m not using buttonWithType:) the button doesn

5条回答
  •  情歌与酒
    2020-11-28 14:35

    I ran into a similar situation, and agree with Jeff that you don't really need to subclass UIButton. I solved this by subclassing UIControl, and then overriding layoutSubviews to do all of the configuration of the views I wanted on my "button". It's a much more simple implementation that subclassing UIButton since there does seem to be some hidden mojo going on under the hood. My implementation looked like this:

    - (id)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
        self.opaque = YES;
    
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:self.imageView];
    
        self.textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        [self addSubview:self.textLabel];
        }
    
    return self;
    }
    

    And layoutSubviews looked like this:

    - (void)layoutSubviews {
    [super layoutSubviews];
    
    // Get the size of the button
    CGRect bounds = self.bounds;
    
    // Configure the subviews of the "button"
    ...
    }
    

提交回复
热议问题