向UIButton添加左右填充

时间:2020-03-31 16:14:06

标签: swift uikit

我想为按钮添加一些左右填充,我看到它们具有titleEdgeInsets属性。这是我的代码:

import UIKit

class QuickPromptButton: UIButton {

    var userFacingValue: String?
    var answerValue: String?

    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.borderColor = UIColor.primaryColor.cgColor
        layer.borderWidth = 1
        layer.cornerRadius = 15
        setTitleColor(.primaryColor, for: .normal)
        titleEdgeInsets = .init(top: 0, left: -10, bottom: 0, right: 10)
        contentVerticalAlignment = .center
        contentHorizontalAlignment = .center

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

但是,这就是他们现在的样子:

enter image description here

问题是文本超出了边界。知道为什么吗?

这就是我在左右两侧都使用10的结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

override var intrinsicContentSize: CGSize {
    let originalSize = super.intrinsicContentSize
    let size = CGSize(width: originalSize.width + 20, height: originalSize.height)
    return size
}

覆盖intrinsicContentSize并在当前宽度的顶部加上总填充量最终对我有用,尽管不确定这是否是正确的方法。