UIButton标题和图像

时间:2017-09-27 09:05:54

标签: ios xcode uibutton

我需要一个按钮,里面有图像,按钮下面有文字。我不能将图像用作背景,因为它会拉伸图像。所以我的问题是如果我使用图像作为按钮,标题将被图像覆盖。对此有什么解决方案吗?

以下是最终应该如何显示的示例:

enter image description here

5 个答案:

答案 0 :(得分:1)

更改标题和图像插入

enter image description here

还将控件从垂直变为底部

enter image description here

答案 1 :(得分:0)

你可以在你喜欢的位置制作一个单独的UIImage和UILabel,并用透明的UIButton覆盖它们。 这应该可以解决问题。

希望它有所帮助。

答案 2 :(得分:0)

您有两个选择

1)创建UIView添加图像,标签和按钮

2)你可以设置标题和图像插入,你可以在XIB中轻松实现

对于选项二,我添加了简单的示例,(将其替换为您的值)

enter image description here

enter image description here

答案 3 :(得分:0)

您可以继承UIButton并重新定义 layoutSubviews 方法。

答案 4 :(得分:0)

您可以调整UIButtonvar titleEdgeInsets: UIEdgeInsetsvar imageEdgeInsets: UIEdgeInsets的以下属性。

另一种方法是继承UIControl。它是UIView子类,旨在用于此类情况。例如,UIButtonUIControl的子类。通过这种方式,您可以更好地控制布局,而且您不需要与UIButton的内置行为作斗争。

您可以使用代码或使用Interface Builder在xib文件中进行布局。

class MyButton: UIControl {

    var imageView: UIImageView
    var label: UILabel

    // adjust colors for changed states like highlighting, etc.
    override var isHighlighted: Bool {
        didSet { 
            if isHighlighted {
                backgroundColor = UIColor.grey              
            } else {
                backgroundColor = UIColor.white             
            }
        }
    }

    override var isSelected: Bool { didSet { ... } }    
    override var isEnabled: Bool { didSet { ... } }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    override init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        imageView = UIImageView(image: UIImage(...))
        addSubView(imageView)
        label = UILabel(frame: CGRect(...))     
        addSubView(label)
        // TODO: add constraints for layout
    }
}