David Kadlcek
David Kadlcek

Reputation: 476

Text and Image inside UIButton

I am stuck in UIButton. I want to add to UIButton text and then next to text add an image, like this: enter image description here

I want to center it.

when I type this:

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)

It shows me: enter image description here

My height breaks and still it doesn't work.

button.alignImageRight()

Means

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

Thanks for every answer.

Upvotes: 0

Views: 1025

Answers (1)

Jay Patel
Jay Patel

Reputation: 2740

Create func for adding 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 }

}

Create extension for UIButton (as you already created). but add UIEdgeInsets in extension.

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)
        }
    }
}

Output

enter image description here

TIP

For auto adjust width depend on Text and Image, use this extension

Upvotes: 2

Related Questions