0

I have this function which inserts a NSTextAttachment into a UITextView. After it is inserted I am wanting to delete a specific bit of text before it updates the textView with the new NSMutableAttributedString. Is there a NSMutableAttributedString function to replace text?

// 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
a.wip
  • 69
  • 12
  • see this for help : https://stackoverflow.com/questions/30468361/ios-nsmutableattributedstring-how-to-delete-last-character-programatically – Anbu.Karthik May 28 '19 at 07:07
  • @Anbu.Karthik I am struggling since I don't have the range of the characters just the string... – a.wip May 28 '19 at 07:09

1 Answers1

1

You need to call replaceCharacters(in:with:), which takes an NSRange and a substitute string. You will clearly need to determine the range first, but that's easy.

matt
  • 515,959
  • 87
  • 875
  • 1,141