iOS 教程:屬性字符串

做者:Arthur Knopper,原文連接,原文日期:2017-04-04ios

譯者:Crystal Sun;校對:way;定稿:shanks

譯者注:本文是以前一篇文章的更新版本,舊文連接,舊文使用的 Swift 版本不是 3.0,本文更新了代碼,升級到了 Swift 3.0。git

屬性字符串(Attributed Strings)能夠爲文本賦予各類各樣的屬性,還能一次給(部分)文本賦值多個屬性。在本節教程中,將學會給 label 文本里的每一個單詞各設置不同的樣式。本節教程使用的是 Xcode 8 和 iOS 10。github

打開 Xcode,建立一個 Single View Application。swift

Product Name 使用 IOS10AttributedStringsTutorial,填寫本身的 Organization Name 和 Organization Identifier,Language 一欄選擇 Swift,Devices 一欄選擇 iPhone。ide

打開 Storyboard,從 Object-Library(控件庫)中拖拽一個 Label 控件到主界面,點擊 Storyboard 右下角 Auto Layout 的 Align 按鈕,添加下圖所示約束,點擊 「Add 1 Constraint」。。ui

點擊 Auto Layout 的 Pin 按鈕,添加以下圖所示約束,點擊 「Add 1 Constraint」。spa

點擊 Assistant Editor,確保 ViewController.swift 文件可見。按住 Control 鍵,將 Label 控件拖拽到 ViewController 類下面,建立下列 Outlet 鏈接。翻譯

打開 ViewController.swift 文件,以下所示對 viewDidLoad 方法進行修改。code

override func viewDidLoad() {
    super.viewDidLoad()
        
    // 1
    let string = "Testing Attributed Strings"
    let attributedString = NSMutableAttributedString(string: string)
        
    // 2
    let firstAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.blue, NSBackgroundColorAttributeName: UIColor.yellow, NSUnderlineStyleAttributeName: 1]
    let secondAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.red, NSBackgroundColorAttributeName: UIColor.blue, NSStrikethroughStyleAttributeName: 1]
    let thirdAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.green, NSBackgroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 40)]
        
    // 3
    attributedString.addAttributes(firstAttributes, range: NSRange(location: 0, length: 8))
    attributedString.addAttributes(secondAttributes, range: NSRange(location: 8, length: 11))
    attributedString.addAttributes(thirdAttributes, range: NSRange(location: 19, length: 7))
        
    // 4
    attributedLabel.attributedText = attributedString
}
  1. 建立一個普通的字符串,將會轉換成多種屬性字符串。對象

  2. 建立見 3 個字典,存儲屬性的鍵和值。

  3. 將屬性添加到 attributedString 對象中。

  4. 最後,將屬性字符串賦值給 Label。

運行程序,屬性字符串的實現效果以下。

能夠從 github 上下載 IOS10AttributedStringsTutorial 教程的源代碼。

本文由 SwiftGG 翻譯組翻譯,已經得到做者翻譯受權,最新文章請訪問 http://swift.gg

相關文章
相關標籤/搜索