textView设置选中之后文字和字体颜色改变
时间: 2023-09-12 19:12:53 浏览: 207
您可以使用 `UITextViewDelegate` 中的 `textViewDidChangeSelection` 方法来实现选中文本后文字和字体颜色的改变。
首先,您需要在 `UITextView` 的 `delegate` 方法中设置 `delegate`:
```swift
yourTextView.delegate = self
```
然后,在 `textViewDidChangeSelection` 方法中添加以下代码:
```swift
func textViewDidChangeSelection(_ textView: UITextView) {
let selectedRange = textView.selectedRange
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText)
attributedText.addAttribute(.foregroundColor, value: UIColor.red, range: selectedRange)
attributedText.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 16), range: selectedRange)
textView.attributedText = attributedText
}
```
这将使选定的文本的颜色变为红色,并将字体加粗为系统字体大小为16。
如果您希望将其还原为默认颜色和字体,请使用以下代码:
```swift
func textViewDidChangeSelection(_ textView: UITextView) {
let selectedRange = textView.selectedRange
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText)
attributedText.removeAttribute(.foregroundColor, range: selectedRange)
attributedText.removeAttribute(.font, range: selectedRange)
textView.attributedText = attributedText
}
```
这将删除选定文本的颜色和字体属性,将其还原为默认值。
阅读全文
相关推荐














