UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

NSMutableAttributedString and clipped backgrounds

Forums > SwiftUI

Hello all. I have a need to replace the font for a specific character in a longer text string. I've been able to successfully acomplish this with Attibutedstrings. I have also been able to adjust the background color of this character to make it stand out. Now what i need to accomplish is turn that rectangular background color into a circle. I have not been able to find a way to do this with the attributed string. Is there a way to add rounded corners and/or a colored circle behind character using AttributedStrings?

Here is a sample of the code i am currently using. Again, this does work, but i would like to round the corners of the background into a circle.

let str = NSMutableAttributedString(string: strIn)
if strIn.contains("") {
        let substringRangeG = strIn.range(of: "")!
        let nsRangeG = NSRange(substringRangeG, in: strIn)
        str.addAttributes([.font: UIFont(name: "customFont", size: 16.0)!,.backgroundColor: UIColor(.green)], range: nsRangeG)
    }

Thanks in advance!

3      

just giving this a bump. does anyone have any suggestions?

3      

No way to do this with just NSAttributedString, I'm afraid. About the closest you could come would be to use a font that has circled characters and replace the uncircled character with its circled counterpart. But I don't think that would work with your background.

You could delve into using NSLayoutManager and try the approach used here: Adding custom attribute to NSAttributedString on iOS

3      

Thanks @roosterboy. If i was to use NSTextAttachment and insert images of my custom font symbols with the circled background instead of swapping font types, is there a way to use ranges to add the NSTextAttachement, or would i just need to parse through my string picking appart the start and end portions and using append to put it back together with the image inserted in the middle?

I am trying to acheive something like this, inserted into a text string replacing that specific character with the colored background version.

Text("C")
    .foregroundColor(.white)
    .padding(10)
    .background(Color(.gray))
    .clipShape(Circle())

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.