1

I have some text in my attributed string that I am trying to remove. How can I do this without removing the attributes?

What I've tried:

I found this post on SO (Replace substring of NSAttributedString with another NSAttributedString) where OP is looking for the equivalent method to NSString's stringByReplacingOccurrencesOfString:withString: for NSAttributedString. I am new to Swift so I couldn't understand the accepted answer.

I moved on to the other answers and if they weren't written in objective c, they were methods that I could not get to compile.

This is as far as I have been able to get. I couldn't find any other posts on SO with a solution to my problem.

6
  • 1
    Have you looked at the documentation for NSMutableAttributedString? Commented Dec 5, 2017 at 22:28
  • I have but cannot figure out if what I am trying to do is possible. Commented Dec 5, 2017 at 22:30
  • Update your question with what you have tried so far. Commented Dec 5, 2017 at 22:31
  • Just updated it. Commented Dec 5, 2017 at 22:38
  • 1
    You don't need to look for other answers. Look at the documentation. There is a clear method for removing part of a mutable attributed string. You just need a range. Commented Dec 5, 2017 at 22:39

1 Answer 1

8

To remove part of an attributed string you need to use the NSMutableAttributedString deleteCharacters(in:) method.

Here's some sample code:

// Create some attributes string
let attrs: [NSAttributedStringKey: Any] = [ .foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 24) ]
let attrStr = NSAttributedString(string: "Hello there", attributes: attrs)
print(attrStr)

// Create a mutable attributed string, find the range to remove and remove it
let mutStr = attrStr.mutableCopy() as! NSMutableAttributedString
let range = (mutStr.string as NSString).range(of: " there")
mutStr.deleteCharacters(in: range)
print(mutStr)

Output:

Hello there{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}
Hello{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.