I want to set NSString's background cornerRadius on iOS7. But,NSString don't have layer...
Please tell me, how to set NSString's background cornerRadius on iOS7?
example
I want to set NSString's background cornerRadius on iOS7. But,NSString don't have layer...
Please tell me, how to set NSString's background cornerRadius on iOS7?
example
NSString doesn't have that. NSAttributedString has a backgroundColor property that can be used but without custom rendering, you won't be able to set a corner radius for the selection of text fragments.
So you need to write a custom UIView to render your text
As a complement to @Emmanuel's solution, adding
will make it look much better.
An
NSString
just defines a string of text. It doesn't define the properties of how it is rendered. For showing text on the screen, usually aUILabel
orUITextView
is used. However, for the selection behavior that you're showing in your example, you'll need to do that drawing yourself. Also it is changing the text color of the selected text, so you'll need to handle doing that yourself.If you created a custom
UIView
that allows you to draw the blue selection area, you could place that behind aUILabel
, and you could use anNSAttributedString
to set the text of the label where the "selected" text is white instead of black. That would probably be the simplest way to do this.Emmanuel's code in swift:
Update to Swift 3.1 Emmanuel's code in swift updated to version 3.1
You can do this by using an
UITextView
with a subclass ofNSLayoutManager
, that override-fillBackgroundRectArray:count:forCharacterRange:color:
. Just a little sample how to this :