Label under image in UIButton

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

    If you subclass UIButton and override layoutSubviews, you can use the below to center the image and place the title centered below it:

    kTextTopPadding is a constant you'll have to introduce that determines the space between the image and the text below it.

    -(void)layoutSubviews {
        [super layoutSubviews];
    
        // Move the image to the top and center it horizontally
        CGRect imageFrame = self.imageView.frame;
        imageFrame.origin.y = 0;
        imageFrame.origin.x = (self.frame.size.width / 2) - (imageFrame.size.width / 2);
        self.imageView.frame = imageFrame;
    
        // Adjust the label size to fit the text, and move it below the image
        CGRect titleLabelFrame = self.titleLabel.frame;
        CGSize labelSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font
                                            constrainedToSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)
                                            lineBreakMode:NSLineBreakByWordWrapping];
        titleLabelFrame.size.width = labelSize.width;
        titleLabelFrame.size.height = labelSize.height;
        titleLabelFrame.origin.x = (self.frame.size.width / 2) - (labelSize.width / 2);
        titleLabelFrame.origin.y = self.imageView.frame.origin.y + self.imageView.frame.size.height + kTextTopPadding;
        self.titleLabel.frame = titleLabelFrame;
    
    }
    

提交回复
热议问题