如何在 Swift 中更改一個 UILabel 的字型大小?


你可以透過將 UILabel 的 font 屬性設定為帶有所需點數大小的 UIFont 物件,來更改 Swift 中 UILabel 的字型大小。

下面是基本設定的程式碼

import UIKit
class TestController: UIViewController {
    
    private let messageLabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initialSetup()
    }
    
    private func initialSetup() {
        
        // basic setup
        view.backgroundColor = .white
        navigationItem.title = "UILabel"
        
        // label customization
        messageLabel.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        messageLabel.numberOfLines = 0
        
        // adding the constraints to label
        view.addSubview(messageLabel)
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        messageLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
        messageLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
    }
}

輸出

在上方的輸出中,你可以看到一個帶有預設字型大小的標籤。

這裡有一個更改字型大小的示例

messageLabel.font = UIFont.systemFont(ofSize: 20)

輸出

在這個示例中,messageLabel 的字型大小被設定為 20 點。你可以調整 fontSize 的值來相應地更改字型大小。

你還可以更改字型粗細,除了更改字型大小。這裡有一個示例

messageLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold)

輸出

另一個選項是使用你的字型名稱和特定大小來建立 UIFont

messageLabel.font = UIFont.init(name: "AmericanTypewriter", size: 20)

輸出

在上方的示例中,你更改了自定義字型。

結論

你可以很容易地更改 UILabel 的字型大小。font 屬性用於分配帶有大小的字型。你也可以根據需要分配自定義字型。UIFont.init(name: "font_name", size: font_size) 方法用於提供帶有大小的自定義字型。

更新於: 2023 年 9 月 7 日

2K+ 觀看次數

開啟你的 職業生涯

完成課程並獲得認證

開始入門
廣告