Label under image in UIButton

后端 未结 30 2009
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:53

I\'m trying to create a button which has some text beneath the icon (sorta like the app buttons) however it seems to be quite difficult to achieve. Any ideas how can I go ab

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 16:20

    I think one of the best ways to do that is by subclassing UIButton and override some rendering methods:

    - (void)awakeFromNib
    {
        [super awakeFromNib];
        [self setupSubViews];
    }
    
    - (instancetype)init
    {
        if (self = [super init])
        {
            [self setupSubViews];
        }
        return self;
    }
    
    - (void)setupSubViews
    {
        [self.imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.imageView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
        [self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageView][titleLabel]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:@{@"imageView": self.imageView, @"titleLabel": self.titleLabel}]];
    }
    
    - (CGSize)intrinsicContentSize
    {
        CGSize imageSize = self.imageView.image.size;
        CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: self.titleLabel.font}];
        return CGSizeMake(MAX(imageSize.width, titleSize.width), imageSize.height + titleSize.height);
    }
    

提交回复
热议问题