在 iOS 應用程式中如何在 TextView 中建立多種樣式?


要建立文字檢視中的多種樣式,我們需要使用屬性化的字串。iOS 中的文字檢視有一個名為 attributedText 的屬性,可用於為文字檢視中的文字設定樣式。我們以一個示例來了解這一點。

首先,我們建立一個屬性

let attributeOne : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 16.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.blue]

然後,使用我們建立的屬性建立一個屬性化的字串

let string = NSAttributedString(string: "Text for first Attribute", attributes: attributeOne)

同樣,我們建立另一個具有不同屬性的字串。然後,使用屬性化的字串初始化 textView 的文字。

現在,整個程式碼應如下所示。

let tx = UITextView()
   tx.isScrollEnabled = true
   tx.isUserInteractionEnabled = true
   tx.frame = CGRect(x: 10, y: 25, width: self.view.frame.width, height: 100)
   let attributeOne : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 16.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.blue]
   let attributeTwo : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize: 20.0), NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : UIColor.red]
   let string = NSAttributedString(string: "Text for first Attribute", attributes: attributeOne)
   let string2 = NSAttributedString(string: "Text for first Attribute", attributes: attributeTwo)
   let finalAttributedString = NSMutableAttributedString()
   finalAttributedString.append(string)
   finalAttributedString.append(string2)
   tx.attributedText = finalAttributedString
   self.view.addSubview(tx)

當我們在 viewDidLoad 或 viewWillAppear 中應用程式中編寫此程式碼時,它將建立如下所示的 textView。

更新於:30-Jul-2019

401 次瀏覽

啟動您的 職業生涯

完成課程以獲得認證

開始
廣告