首页 > 解决方案 > 删除 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

标签: iosswift

解决方案


您需要调用replaceCharacters(in:with:)NSRange 和替代字符串。您显然需要先确定范围,但这很容易。


推荐阅读