作者:Arthur Knopper,原文鏈接,原文日期:2017-04-04
譯者:Crystal Sun;校對:way;定稿:shanks
譯者注:本文是之前一篇文章的更新版本,舊文鏈接,舊文使用的 Swift 版本不是 3.0,本文更新了代碼,升級到了 Swift 3.0。
屬性字符串(Attributed Strings)可以為文本賦予各種各樣的屬性,還能一次給(部分)文本賦值多個(gè)屬性。在本節(jié)教程中,將學(xué)會(huì)給 label 文本里的每個(gè)單詞各設(shè)置不一樣的樣式。本節(jié)教程使用的是 Xcode 8 和 iOS 10。
打開 Xcode,創(chuàng)建一個(gè) Single View Application。
Product Name 使用 IOS10AttributedStringsTutorial,填寫自己的 Organization Name 和 Organization Identifier,Language 一欄選擇 Swift,Devices 一欄選擇 iPhone。
打開 Storyboard,從 Object-Library(控件庫)中拖拽一個(gè) Label 控件到主界面,點(diǎn)擊 Storyboard 右下角 Auto Layout 的 Align 按鈕,添加下圖所示約束,點(diǎn)擊 “Add 1 Constraint”。。
點(diǎn)擊 Auto Layout 的 Pin 按鈕,添加如下圖所示約束,點(diǎn)擊 “Add 1 Constraint”。
點(diǎn)擊 Assistant Editor,確保 ViewController.swift 文件可見。按住 Control 鍵,將 Label 控件拖拽到 ViewController 類下面,創(chuàng)建下列 Outlet 連接。
打開 ViewController.swift 文件,如下所示對 viewDidLoad 方法進(jìn)行修改。
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
}
- 創(chuàng)建一個(gè)普通的字符串,將會(huì)轉(zhuǎn)換成多種屬性字符串。
- 創(chuàng)建見 3 個(gè)字典,存儲屬性的鍵和值。
- 將屬性添加到
attributedString對象中。 - 最后,將屬性字符串賦值給 Label。
運(yùn)行程序,屬性字符串的實(shí)現(xiàn)效果如下。
可以從 github 上下載 IOS10AttributedStringsTutorial 教程的源代碼。
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權(quán),最新文章請?jiān)L問 http://swift.gg。