我遇到的問題是我希望能夠更改TextView中某些文本的textColor。我使用的是串聯字符串,只希望將字符串追加到TextView的文本中。看來我想使用的是NSMutableAttributedString,但是在Swift中找不到如何使用它的任何資源。到目前為止,我有這樣的事情:let string = "A \(stringOne) with \(stringTwo)"var attributedString = NSMutableAttributedString(string: string)textView.attributedText = attributedString從這里我知道我需要找到需要更改其textColor的單詞范圍,然后將它們添加到屬性字符串中。我需要知道的是如何從attributedString中查找正確的字符串,然后更改其textColor。由于我的評分太低,我無法回答自己的問題,但這是我找到的答案我通過翻譯一些代碼來找到自己的答案更改NSAttributedString中子字符串的屬性這是Swift中的實現示例:let string = "A \(stringOne) and \(stringTwo)"var attributedString = NSMutableAttributedString(string:string)let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))for stringOneMatch in stringOneMatches { let wordRange = stringOneMatch.rangeAtIndex(0) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)}textView.attributedText = attributedString由于我想更改多個字符串的textColor,因此我將創建一個輔助函數來處理此問題,但這可用于更改textColor。
3 回答

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
Swift 2.1更新:
let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
let linkTextWithColor = "click here"
let range = (text as NSString).rangeOfString(linkTextWithColor)
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
self.helpText.attributedText = attributedString
self.helpText是一個UILabel出口。
- 3 回答
- 0 關注
- 1737 瀏覽
添加回答
舉報
0/150
提交
取消