文字上方的UIButton图片

时间:2019-01-31 20:34:52

标签: ios swift uibutton

我有两个动态尺寸按钮,我需要为其制作图像和标题文本。图片必须在顶部,文字必须在按钮下方,并且两者都必须在按钮的中央。我尝试用imageEdgeInsatse来做,但是不明白我做错了什么。

这是我的代码:

leftButton.imageEdgeInsets = UIEdgeInsets(top: 5, left:0, bottom: 60, right: 0)
leftButton.titleEdgeInsets = UIEdgeInsets(top: 60, left: 0, bottom: 5, right: 0)

rightButton.imageEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 60, right: 0)
rightButton.titleEdgeInsets = UIEdgeInsets(top: 60, left: 0, bottom: 5, right: 0)

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试使用此代码扩展名。

extension UIButton {
    func alignVertical(spacing: CGFloat = 6.0) {
        guard let imageSize = self.imageView?.image?.size,
            let text = self.titleLabel?.text,
            let font = self.titleLabel?.font
            else { return }
        self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
        let labelString = NSString(string: text)
        let titleSize = labelString.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: font])
        self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
        let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
        self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
    }
}

像这样使用扩展名

override func viewDidLayoutSubviews() {
    button.alignVertical()
}