[英]2 UIButton with dynamic text and font size
我在同一個 y position 中使用 2 UIButton
左邊的文本比右邊的短:
我正在添加
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.5
對於每個按鈕。 The problem is that one button font size get smaller than the other
。 例如,它們的字體大小都是 18,一個可能是 12,另一個將保持 18。我希望它們都是 15(更大的可能使兩個文本都可見)
插入按鈕的文本發生變化,因此我無法使用縱橫比。
另外,我不想將按鈕的字體與較小的文本一起使用,因為有時差異很大。
您可以使用堆棧視圖以編程方式執行此操作,在您的 controller class 下聲明您的按鈕:
let myButton: UIButton = {
let b = UIButton()
b.backgroundColor = .white
b.setTitle("Short button", for: .normal)
b.setTitleColor(.black, for: .normal)
b.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
b.layer.cornerRadius = 12
b.clipsToBounds = true
b.titleLabel?.adjustsFontSizeToFitWidth = true
b.titleLabel?.minimumScaleFactor = 0.5
b.translatesAutoresizingMaskIntoConstraints = false
return b
}()
let myButton2: UIButton = {
let b = UIButton()
b.backgroundColor = .white
b.setTitle("Much Much Much longer button", for: .normal)
b.setTitleColor(.black, for: .normal)
b.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
b.layer.cornerRadius = 12
b.clipsToBounds = true
b.titleLabel?.adjustsFontSizeToFitWidth = true
b.titleLabel?.minimumScaleFactor = 0.5
b.translatesAutoresizingMaskIntoConstraints = false
return b
}()
現在在 viewDidLoad 中設置 stackView 和約束(我為空間設置了 6,但你可以設置你喜歡的空間,看評論來做):
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
let stackView = UIStackView(arrangedSubviews: [myButton, myButton2])
stackView.distribution = .fillProportionally
stackView.spacing = 6 // change space betwenn buttons
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
這是 shortButton/shortButton 和 shortButton/longerButton 的結果,按鈕的寬度根據文本動態變化:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.