uikituibutton

UIButton/Configuration titleAlignment = .leading and imagePlacement = .trailing are not respected


        var configuration = UIButton.Configuration.bordered()
        configuration.image = ImageProvider.icon.history
        configuration.imagePlacement = .trailing
        historyButton.configuration = configuration
        configuration.titleAlignment = .leading
        historyButton.setTitle(String(localized: "History"), for: .normal)
        let image = ImageProvider.icon.history
        historyButton.setImage(image, for: .normal)

Centered for some reason

How could I get the title tethered to the leading edge of the button and image to the trailing edge? Thanks!

Changing alignment to leading moves both title and the image to the leading edge.

enter image description here


Solution

  • The key is setting the button's .contentHorizontalAlignment to .fill...

    var configuration = UIButton.Configuration.bordered()
    configuration.image = UIImage(systemName: "gobackward.15")
    configuration.title = "History"
    configuration.imagePlacement = .trailing
    let btn = UIButton(configuration: configuration)
        
    btn.contentHorizontalAlignment = .fill
        
    btn.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(btn)
    let g = view.safeAreaLayoutGuide
    NSLayoutConstraint.activate([
        btn.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
        btn.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 60.0),
        btn.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -60.0),
    ])
    

    Result:

    enter image description here