Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a border around a paragraph in UILabel?

I am attempting to use a UILabel that can show rich content. For this I use the attributedText property in UILabel and a NSAttributedString I alloc with NSHTMLTextDocumentType.

One type of formatting I want to achieve is to draw a border around paragraphs (for quotes). Normal text formatting like font, bold, italic etc seems to work fine, but when I use CSS properties like border it does not work as I would expect. See picture; only the background-color property is shown.

UILabel with HTML

The attributedText property of this UILabel is:

<style>
  body{font:10pt Verdana;} .quote {background-color:#ddd;border:1px solid #aaa;}
</style>
<body>
  <div class="quote">This is a quote</div>
  <br/>
  Bla bla bla
</body>

What I expect is a border around the first sentence/paragraph, within the UILabel - not a border around the entire UILabel.

The text background shows, but the expected border does not. Is it even possible to achieve this? I'd prefer to use UILabel to keep my UITableView speedy.

like image 721
pojo Avatar asked Mar 22 '23 01:03

pojo


1 Answers

I'm not aware of this being implemented in the SDK, even if you can restrict to iOS 7. There are at least two general options though.

In a subclass of UILabel you can use the sizing methods of NSAttributedString, such as boundingRectWithSize:options:context: and size, to calculate where the subtext is to appear, and in an override of drawTextInRect: draw the border. You might deduce the required border frame by calculating the frame for the preceding text and for the subtext appended and then taking their difference.

Another option is to set custom attributes on your NSAttributedStrings, something Apple openly encourages, from Apple's overview:

You can assign any attribute name/value pair you wish to a range of characters—it is up to your application to interpret custom attributes (see Attributed String Programming Guide).

Then in a subclass of NSAttributedStrings, override the drawing methods such as drawInRect: and implement similar custom drawing logic per the first suggestion for your custom attribute, otherwise rely on super.

like image 66
SK9 Avatar answered Apr 24 '23 21:04

SK9