Home > database >  IOS 15 UIButton right alignment not working
IOS 15 UIButton right alignment not working

Time:04-12

In IOS 15, Even after setting button text alignment to right, it leaves little space after the button title text. As shown in the following image it leaves the space after the word Test. How can I remove this space? I want the letter "t" in the text to touch the trailing of the button.

enter image description here

In ios 14 and below it looks like this

enter image description here

CodePudding user response:

You can try using this with DispatchQueue

button.contentHorizontalAlignment = .left
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)

CodePudding user response:

This is a little trick or you can do it with UIButton.Configuration, set your button like this:

let myButton: UIButton = {
    let b = UIButton()
    b.backgroundColor = .white
    b.tintColor = .black
    b.layer.cornerRadius = 8
    b.clipsToBounds = true
    b.setTitle(" My button Test", for: .normal) // space in front of string = space fron text and image
    b.setTitleColor(.black, for: .normal)
    b.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
    b.contentHorizontalAlignment = .right
    b.setImage(UIImage(systemName: "bag"), for: .normal)
    b.configuration?.imagePlacement = .leading // use button configuration to add image position
    b.translatesAutoresizingMaskIntoConstraints = false

    return b
}()

This is UIButton.Configuration style:

let myButton: UIButton = {
    
    var filled = UIButton.Configuration.filled()
    filled.title = "My button Test"
    filled.buttonSize = .large
    filled.baseBackgroundColor = .white
    filled.baseForegroundColor = .black
    filled.cornerStyle = .medium
    filled.image = UIImage(systemName: "bag", withConfiguration: UIImage.SymbolConfiguration(scale: .large))
    filled.imagePlacement = .leading
    filled.imagePadding = 4
    filled.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

    let b = UIButton(configuration: filled, primaryAction: nil)
    b.contentHorizontalAlignment = .right
    b.translatesAutoresizingMaskIntoConstraints = false

    return b
}()

in viewDidLoad present button and set constraints:

view.addSubview(myButton)
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true

This is the result:

enter image description here

  • Related