ios - UIButton 中图像下的标签

标签 ios image text uibutton label

我正在尝试创建一个在图标下方有一些文本的按钮(有点像应用程序按钮),但它似乎很难实现。有什么想法可以让文本显示在 带有 UIButton 的图像下方吗?

最佳答案

或者你可以只使用这个类别:

对象

@interface UIButton (VerticalLayout)

- (void)centerVerticallyWithPadding:(float)padding;
- (void)centerVertically;

@end

@implementation UIButton (VerticalLayout)

- (void)centerVerticallyWithPadding:(float)padding {
    CGSize imageSize = self.imageView.frame.size;
    CGSize titleSize = self.titleLabel.frame.size;
    CGFloat totalHeight = (imageSize.height + titleSize.height + padding);
    
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height),
                                            0.0f,
                                            0.0f,
                                            - titleSize.width);
    
    self.titleEdgeInsets = UIEdgeInsetsMake(0.0f,
                                            - imageSize.width,
                                            - (totalHeight - titleSize.height),
                                            0.0f);
    
    self.contentEdgeInsets = UIEdgeInsetsMake(0.0f,
                                              0.0f,
                                              titleSize.height,
                                              0.0f);
}

- (void)centerVertically {
    const CGFloat kDefaultPadding = 6.0f;
    [self centerVerticallyWithPadding:kDefaultPadding];
}

@end

快速扩展

extension UIButton {
    
    func centerVertically(padding: CGFloat = 6.0) {
        guard
            let imageViewSize = self.imageView?.frame.size,
            let titleLabelSize = self.titleLabel?.frame.size else {
            return
        }
        
        let totalHeight = imageViewSize.height + titleLabelSize.height + padding
        
        self.imageEdgeInsets = UIEdgeInsets(
            top: -(totalHeight - imageViewSize.height),
            left: 0.0,
            bottom: 0.0,
            right: -titleLabelSize.width
        )
        
        self.titleEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: -imageViewSize.width,
            bottom: -(totalHeight - titleLabelSize.height),
            right: 0.0
        )
        
        self.contentEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: 0.0,
            bottom: titleLabelSize.height,
            right: 0.0
        )
    }
    
}

建议: 如果按钮高度小于 totalHeight,则图像将绘制外边框。

imageEdgeInset.top 应该是:

max(0, -(totalHeight - imageViewSize.height))

关于ios - UIButton 中图像下的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201959/

相关文章:

text - 为什么 CGContextSetRGBStrokeColor 不适用于 ios7?

ios - 制作Yajl iOS框架文件

ios - Sprite 套件项目在设备而非模拟器上构建和运行

ios - 如何更改按钮大小?

image - 图像链接中的 html/css 透明度不可点击

javascript - Tomcat 404错误,找不到图片js和css

variables - 带有 knockout 功能的链接中的可变文本

ios - 保存 NSDate 后忽略时区更改

带有图像文件的 Java 项目

python - 在计算文本文档集合中的单词出现次数时遇到问题