Rightpoint / BonMot

Beautiful, easy attributed strings in Swift
MIT License
3.56k stars 197 forks source link

replace specific XML tags with UIImage. #321

Closed hakim89 closed 6 years ago

hakim89 commented 6 years ago

I need to add bootstrap-like badges in my attributedString. For example I need to replicate this HTML in a UILabel in Swift using BonMot library:

screen shot 2018-02-06 at 5 11 10 pm

I run some regex on my string to create a XML tag that looks like this <badge>abbreviation</badge> which i'm trying to make it look like the HTML.

My first approach was to style that tag to look like a badge but couldn't make it look exactly like a badge.

Second approach is to replace it with an image. I have some code to make a UIImage from any string. For example: "abbreviation".toBadgeImage() will create an image that looks like this.

screen shot 2018-02-06 at 5 16 11 pm

Next step where i'm stuck is replacing that XML tag with the resulting UIImage.

would greatly appreciate any input on how to take this functionality to the finish line.

ZevEisenberg commented 6 years ago

Hey, @hakim89. You should be able to add an enter rule that will handle this for you. You can see an example in the demo project: https://github.com/Raizlabs/BonMot/blob/master/Example-iOS/DemoStrings.swift#L61. Please check that out, and let me know if you run into any problems.

hakim89 commented 6 years ago

Hey @ZevEisenberg, thank you very much for your suggestion. I converted the badges to xml tags that looks like this <badge:abbreviation/> and I was able to replace that with XMLStyleRule.enter It worked but now I am facing another problem is that the UIImage (the one I inserted as a badge) is tinted with the .color() rule that was added too.

screen shot 2018-02-06 at 8 42 31 pm

Those are my styles.


let mainStyle = StringStyle(
            .font(DictionaryCell.mainFont),
            .lineHeightMultiple(1.0),
            .color(baseColor),
            .xmlRules([
                .style("strong", strongStyle),
                .style("itl", italicStyle),
                .style("sup", supStyle),
                .style("sub", subStyle),
                .style("rnd-bracket", rndBracketStyle),
                .style("sqr-bracket", squareBracketStyle),
                ] + badgeStyleList)
        )

Anyway you know around that?

ZevEisenberg commented 6 years ago

Good question! The image is being tinted because the default rendering mode for a UIImage is automatic. You should be able to set it to alwaysOriginal via myImage.withRenderingMode(.alwaysOriginal), and BonMot will respect that and not tint the image.

hakim89 commented 6 years ago

Thank you very much for your help. It all worked well.