UITextView 选中文本的颜色

4
如果我有一个`UITextView`且`textview.selectable = true`,我想使用一个`UIButton`来更改所选文本的颜色,我应该如何使用 Swift 实现此功能?

你找到解决方法了吗?如果是,请发布正确的答案。 - Cesare
1个回答

8

如果您只想更改字符串的选定范围,则必须更改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
}

如果您想更改整个字符串,可以使用CeceXX提出的技术。
@IBAction func didTapButton(sender: UIButton) {
    textView.textColor = UIColor.redColor()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接