Label under image in UIButton

后端 未结 30 2068
佛祖请我去吃肉
佛祖请我去吃肉 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:28

    I found that Simeon's answer was probably the best but it was giving me strange results on some buttons and I just couldn't work out why. So using his answer as a base I implemented my buttons as per below:

    #define PADDING 2.0f
    
    @implementation OOButtonVerticalImageText
    
    -(CGSize) intrinsicContentSize {
      CGSize size = [super intrinsicContentSize];
      CGFloat labelHeight = 0.0f;
      CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake([self contentRectForBounds:self.bounds].size.width, CGFLOAT_MAX)];
      labelHeight = titleSize.height;
      return CGSizeMake(MAX(titleSize.width, self.imageView.image.size.width), self.imageView.image.size.height + labelHeight + PADDING);
    }
    
    -(void) layoutSubviews {
      [super layoutSubviews];
    
      CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake([self contentRectForBounds:self.bounds].size.width, CGFLOAT_MAX)];
      self.titleLabel.frame = CGRectMake((self.bounds.size.width - titleSize.width)/2.0f,
                                         self.bounds.size.height - titleSize.height - PADDING,
                                         titleSize.width,
                                         titleSize.height);
    
      CGSize ivSize = self.imageView.frame.size;
      self.imageView.frame = CGRectMake((self.bounds.size.width - ivSize.width)/2.0f,
                                        self.titleLabel.frame.origin.y - ivSize.height - PADDING,
                                        ivSize.width,
                                        ivSize.height);
    }
    
    @end
    

提交回复
热议问题