As sizeToFit
will ignore titleEdgeInsets
settings. In my case, the button title is fixed text, so I use autolayout to give each button a width constraint.
And I think if dynamic text length, you need to get the string size first and update the button constraint in viewDidLayoutSubview
.
lazy var importButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Import", for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 18, weight: .bold)
btn.setTitleColor(.white, for: .normal)
btn.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
btn.backgroundColor = .myBlue
btn.layer.cornerRadius = 8
btn.clipsToBounds = true
btn.addTarget(self, action: #selector(importButtonTapped), for: .touchUpInside)
return btn
}()
lazy var stitchButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Stitch", for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 18, weight: .bold)
btn.setTitleColor(.white, for: .normal)
btn.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
btn.backgroundColor = .myGreen
btn.layer.cornerRadius = 8
btn.clipsToBounds = true
btn.addTarget(self, action: #selector(stitchButtonTapped), for: .touchUpInside)
return btn
}()
func setViews() {
title = "Image Stitcher"
view.backgroundColor = .systemBackground
view.addSubview(importButton)
view.addSubview(stitchButton)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
NSLayoutConstraint(item: importButton, attribute: .centerX, relatedBy: .equal, toItem: g, attribute: .trailing, multiplier: 0.3, constant: 0),
importButton.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -50),
importButton.widthAnchor.constraint(equalTo: g.widthAnchor, multiplier: 0.25),
importButton.heightAnchor.constraint(equalTo: importButton.widthAnchor, multiplier: 0.5),
NSLayoutConstraint(item: stitchButton, attribute: .centerX, relatedBy: .equal, toItem: g, attribute: .trailing, multiplier: 0.7, constant: 0),
stitchButton.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -50),
stitchButton.widthAnchor.constraint(equalTo: g.widthAnchor, multiplier: 0.25),
stitchButton.heightAnchor.constraint(equalTo: stitchButton.widthAnchor, multiplier: 0.5),
])
}
