ios - 删除 NSMutableAttributedString 中的特定文本
问题描述
我有这个将 a 插入NSTextAttachment
到 a中的函数UITextView
。插入后,我想在用新的 .textView 更新之前删除特定的文本位NSMutableAttributedString
。有没有NSMutableAttributedString
替换文字的功能?
// Create Attachment
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(origin: .zero, size: image.size)
// Current Attributed String
var atStr = NSMutableAttributedString(attributedString: textView.attributedText)
// Insert Attachment
let attachmentAtStr = NSAttributedString(attachment: attachment)
if let selectedRange = textView.selectedTextRange {
let cursorIndex = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
atStr.insert(attachmentAtStr, at: cursorIndex)
atStr.addAttributes(self.textView.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
} else {
atStr.append(attachmentAtStr)
}
// Delete Specific Text (ERROR: Value of type 'NSMutableAttributedString' has no member 'replacingOccurrences')
atStr = atStr.replacingOccurrences(of: "text to replace", with: "replacement", options: [.caseInsensitive, .regularExpression])
textView.attributedText = atStr
解决方案
您需要调用replaceCharacters(in:with:)
NSRange 和替代字符串。您显然需要先确定范围,但这很容易。
推荐阅读
- c++ - 从 VideoCapture 转换为 Mat 对象后,图像高度减半
- c - C中的fgets函数和文件处理
- mysql - “SELECT * FROM book WHERE year=wyear AND account >= waccount1 AND account <= waccount1”
- python - 如何在 Python 中创建可更新的元组列表?
- excel - 插入行和填充的宏失败
- r - 使用 `readxl` 包对彩色单元格进行分类
- .net - 部署 dotnet 核心应用程序
- processing - 如何不覆盖现有的对象列表?
- asp.net-mvc - 使用服务工作者从服务器获取要缓存的文件列表
- java - 谷歌支付 isReadyToPay 方法返回 false