switch gesture.state { case .changed: // 将触摸位置转换为文本位置 if let textPosition = textView.closestPosition(to: location) { // 获取对应的字符 let range = NSRange(location: textView.offset(from: textView.beginningOfDocument, to: textPosition), length: 1) let attributes = textView.textStorage.attributes(at: range.location, effectiveRange: nil)
// 将字符的前景色设置为和背景色一样的颜色 if let backgroundColor = attributes[NSAttributedString.Key.backgroundColor] as? UIColor { let foregroundColor = backgroundColor.withAlphaComponent(1) textView.textStorage.addAttributes([NSAttributedString.Key.foregroundColor: foregroundColor], range: range) } } case .ended, .cancelled: // 恢复所有字符的前景色 let range = NSRange(location: 0, length: textView.text.count) textView.textStorage.removeAttribute(NSAttributedString.Key.foregroundColor, range: range) default: break } } }