Brandon Cornelio
Brandon Cornelio

Reputation: 343

Remove part of attributed string without removing attributes

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.

Upvotes: 1

Views: 4447

Answers (1)

rmaddy
rmaddy

Reputation: 318794

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";
}

Upvotes: 8

Related Questions