如何在Swift中建立屬性字串?


本文將解釋如何在Swift語言中建立屬性字串。在Swift中,如何為字串應用不同的屬性?

在Swift中,我們使用NSAttributedString類來建立屬性字串。

在Swift中,NSAttributedString是一個用於建立和管理屬性字串的類。屬性字串是指應用了附加屬性(例如文字顏色、字型和樣式)的字串。

本文將展示屬性字串的不同用例。

基本設定

import UIKit
class TestController: UIViewController {
    private let attributedLabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initialSetup()
    }
    private func initialSetup() {
        
        // basic setup
        view.backgroundColor = .white
        navigationItem.title = "NSAttributedString"
        
        
        // attributedLabel customization
        attributedLabel.numberOfLines = 0
        attributedLabel.backgroundColor = UIColor(white: 0, alpha: 0.1)
        
        view.addSubview(attributedLabel)
        attributedLabel.translatesAutoresizingMaskIntoConstraints = false
        attributedLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
        attributedLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
        attributedLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30).isActive = true
        attributedLabel.heightAnchor.constraint(equalToConstant: 300).isActive = true
    }
}

解釋

在上面的程式碼中,我們設定了一個名為TestController的檢視控制器來顯示UILabel類的不同屬性文字。

輸出

如何為整個字串應用顏色?

在這個例子中,您將看到如何為整個字串應用顏色。以下是如何在Swift中建立具有不同屬性的NSAttributedString物件的示例:

private func example1() {
   let string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
   let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.red,
   let attributedString = NSAttributedString(string: string, attributes: attributes)
   attributedLabel.attributedText = attributedString
}

輸出

如何為整個字串應用不同的顏色和字型樣式?

在這個例子中,您將看到如何為字串應用不同的顏色和字型樣式。以下是如何在Swift中建立具有不同屬性的NSAttributedString物件的示例:

private func example2() {
   // first part
   let attributedString = NSMutableAttributedString(string: "This is the first line of black color. We're not applying any attribute to this part of string.",
      attributes: [.foregroundColor: UIColor.black, font: UIFont.systemFont(ofSize: 17)])
        
   // appending new lines
   attributedString.append(NSAttributedString(string: "\n\n"))
        
   // second part
   attributedString.append(NSAttributedString(string: "This part will be in Red color and bold style in the string.", attributes: [.foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 17, weight: .bold)]))
        
   // appending new lines
   attributedString.append(NSAttributedString(string: "\n\n"))
        
   // third part
   attributedString.append(NSAttributedString(string: "This part will be in Brown color and underline style in the string.", attributes: [.foregroundColor: UIColor.brown, .font: UIFont.systemFont(ofSize: 17), .underlineStyle: 1]))
        
   attributedLabel.attributedText = attributedString
}

輸出

如何為整個字串應用行間距?

在許多情況下,您必須為字串應用一些行間距才能正確顯示多行文字。Swift提供NSMutableParagraphStyle類來新增行之間的間距。以下是如何在Swift中將段落樣式應用於字串的示例:

private func example3() {
   let string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
   let paragraph = NSMutableParagraphStyle()
   paragraph.lineSpacing = 7
   let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.red,
      .font: UIFont.systemFont(ofSize: 17),
      .paragraphStyle: paragraph]
   let attributedString = NSAttributedString(string: string, attributes: attributes)
   attributedLabel.attributedText = attributedString
}

輸出

結論

在真實的iOS應用程式中,屬性字串是一個非常有用且常用的功能。您可以為字串應用不同的樣式。此外,您還可以將各種樣式應用於子字串。

更新於:2023年9月7日

499 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.