如果我有一个`UITextView`且`textview.selectable = true`,我想使用一个`UIButton`来更改所选文本的颜色,我应该如何使用 Swift 实现此功能?
如果您只想更改字符串的选定范围,则必须更改attributedText
属性。您可以执行以下操作:
@IBAction func didTapButton(sender: UIButton) {
let range = textView.selectedRange
let string = NSMutableAttributedString(attributedString: textView.attributedText)
let attributes = [NSForegroundColorAttributeName: UIColor.redColor()]
string.addAttributes(attributes, range: textView.selectedRange)
textView.attributedText = string
textView.selectedRange = range
}
@IBAction func didTapButton(sender: UIButton) {
textView.textColor = UIColor.redColor()
}