Feature Request: Highlighting a text range
Asks:
- Ability to highlight a given range of text
- Ability to adjust the size / padding of the highlighting rect
- Should work for the supported text alignment types
Hi @iwasrobbed, and thanks for your feature request. I'd like to find out a little bit more about what you're doing. .backgroundColor(.red) (Swift 3) will draw a box around the text, but you don't get a lot of control over it - just what the system text layout system provides. To get more control, you'd probably need to get the glyph positions using Core Text and do the drawing yourself.
This isn't really in the scope of BonMot, which is mainly for manipulating attributed strings. However, if you needed the ability to set custom attributes on ranges of attributed strings, that's certainly something that could be added.
Also, what did you mean by "should work for the supported text alignment types"?
Hey Zev! I was using highlight in the more traditional sense of when you highlight something in a book, you paint it with a different colored background; as you noted, backgroundColor paints the entire frame itself, not a given range of a string so they are visually very different.
You can do this today using NSBackgroundColorAttributeName but it doesn't allow adjustment of the bounding text rect (i.e. for padding) so it'd more likely involve filling a path of each line / range of text.
This may be outside the scope of BonMot, so if you believe so, feel free to close this
@iwasrobbed BonMot has two facilities for adjusting sub-ranges: you can concatenate elements using -[BONText setNextText:] or -[BONChain appendLink:separatorTextable:], or you can use .tagStyles() on BONChain to specify BONChains for substrings of your main string by using an HTML-like syntax.
However, if you're using BonMot in the context of a user making interactive edits, neither of those is really useful. It might make sense to add a utility to BonMot like -[NSMutableAttributedString addTextable:atRange:]. In lieu of that, it's pretty straightforward to call -[BONChain attributes] to get back the attributes dictionary, and then set that on your attributed string.
If you use BonMot's backgroundColor setter, it does map to NSBackgroundColorAttributeName, but you have to use it with one of the aforementioned methods to apply it to a range, rather than the whole string. But you're correct that you don't get any control over NSBackgroundColorAttributeName, which is why I suggested adding a way for BonMot to set arbitrary attribute key/value pairs on attributed strings.
Let me know if this makes sense, and if any of it sounds like it would be useful to you, I'd be happy to merge a pull request or put an issue in my hack day queue.