如何在 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) 方法用于提供带有大小的自定义字体。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP