簡體   English   中英

以編程方式居中 alignment UIButton xCODE

[英]Center alignment UIButton xCODE programmatically

我正在嘗試以編程方式將 UIButton 的文本居中。

這就是我希望 UIButton 的樣子(我使用了界面生成器):

UIbutton

這是我以編程方式設置 UIButton 后的樣子:

UIbutton

這就是 UIButton 在我以編程方式設置它並嘗試像第一張圖片那樣將文本居中之后的樣子:

UIButton

這是我用來嘗試將其居中的代碼:

previousPageButton.titleLabel?.numberOfLines = 0

previousPageButton.titleLabel?.textAlignment = .center

問題是我在界面生成器中設置了“歸因於”標題。 我只需要將它設置為“普通”,它現在就可以工作了。

用新的按鈕配置來做,設置你的按鈕:

let myButton: UIButton = {
    let b = UIButton()
    b.configuration = UIButton.Configuration.filled()
    b.configuration?.title = "CLICK TO GO TO\n PREVIOUS PAGE"
    b.titleLabel?.textAlignment = .center
    b.configuration?.baseForegroundColor = .white // text color
    b.configuration?.baseBackgroundColor = .black // background color
    b.configuration?.cornerStyle = .small // corner radius
    b.translatesAutoresizingMaskIntoConstraints = false
    
    return b
}()

在 viewDidLoad 中設置約束:

view.addSubview(myButton)
    myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    myButton.heightAnchor.constraint(equalToConstant: 80).isActive = true // set eight of button
    myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true // set width of button

這是結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM