iOS textViewselectedTextRangebackgroundColor = UIColorred 报错
这是因为UITextView的selectedTextRange属性返回的是一个UITextRange对象,而该对象没有backgroundColor属性。如果要设置选中文本的背景色,你可以使用UITextView的selectedTextRange属性获取选中文本的范围,然后使用UITextView的textStorage属性的addAttribute(_:value:range:)方法来设置文本的属性。
以下是一个示例代码:
if let selectedRange = textView.selectedTextRange {
let selectedText = textView.text(in: selectedRange)
let attributedString = NSMutableAttributedString(string: selectedText ?? "")
attributedString.addAttribute(.backgroundColor, value: UIColor.red, range: NSRange(location: 0, length: attributedString.length))
textView.textStorage.replaceCharacters(in: selectedRange, with: attributedString)
}
这个代码段会将选中的文本的背景色设置为红色。请注意,这个代码仅仅设置了选中文本的背景色,如果要取消选中文本的背景色,你可以设置背景色为透明色或者去除该属性
原文地址: https://www.cveoy.top/t/topic/h00I 著作权归作者所有。请勿转载和采集!