UIButton中的文本和图像

时间:2018-06-25 21:18:09

标签: ios swift uibutton

我被困在UIButton中。我要添加到UIButton文本,然后在文本旁边添加图像,例如:enter image description here

我想居中

当我键入此内容时:

let button = UIButton(type: .custom)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Přidat za: \(priceForCategory)", for: .normal)
    button.setImage(UIImage(named: "Coin"), for: .normal)
    button.imageEdgeInsets = UIEdgeInsets(top: 6, left: -100, bottom: 6, right: 6)
    button.titleLabel?.textAlignment = .right
    button.alignImageRight()
    button.imageView?.contentMode = .scaleAspectFit
    button.backgroundColor = UIColor.custom.orange
    button.addTarget(self, action: #selector(handleAddCategory), for: .touchUpInside)
    button.tintColor = .white
    button.titleLabel?.font = UIFont(name: ".SFUIText-Bold", size: 20)

它向我显示:enter image description here

我的身高折断了,但仍然无法正常工作。

button.alignImageRight()

手段

func alignImageRight() {
    if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
        semanticContentAttribute = .forceRightToLeft
    }
    else {
        semanticContentAttribute = .forceLeftToRight
    }
}

感谢每个答案。

1 个答案:

答案 0 :(得分:1)

创建用于添加UIButton的功能

func addRoundedButton() {

    let button = UIButton(type: .custom)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Add for: 100", for: .normal)
    button.setImage(UIImage(named: "Coin"), for: .normal)

    button.alignImageRight()

    //Add this line for rounded corner
    button.layer.cornerRadius = 20  // set cornerRadius = height/2

    button.backgroundColor = UIColor.orange

    button.tintColor = .white
    button.titleLabel?.font = UIFont(name: ".SFUIText-Bold", size: 20)

    view.addSubview(button)

    [button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -15),
    button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    button.heightAnchor.constraint(equalToConstant: 40),
    button.widthAnchor.constraint(equalToConstant: 300)].forEach{ $0.isActive = true }

}

为UIButton创建扩展名(已创建)。但是在扩展中添加UIEdgeInsets。

extension UIButton {

    func alignImageRight() {
        if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
            semanticContentAttribute = .forceRightToLeft
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
        } else {
            semanticContentAttribute = .forceLeftToRight
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)
        }
    }
}

输出

enter image description here

提示

要根据文本和图像自动调整宽度,请使用this extension