I can create a multi-line NSAttributedString
by using escaped new-line characters (@\"\\n\"
). With iOS 7, I can now embed a UIImage
in
Did you try to get the actually height of the text using the boundingRectWithSize method:
NSAttributedString *text;
CGFloat width = 200;
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
CGFloat height = rect.size.height;
I have found another workaround for this bug, which is sufficiently different from my previous answer that I'm providing it as another answer: let the label set its own height.
In this code, I'm removing the height constraint from a label with a fixed width constraint, and replacing it with a greater-than height constraint (and I'm sure there are other ways to achieve the same outcome):
[self.lab removeConstraint:self.labelHeight];
[self.lab addConstraint:
[NSLayoutConstraint constraintWithItem:self.lab
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:nil attribute:0 multiplier:1 constant:20]];
That label displays correctly every attributed string I throw at it! Of course, you lose the automatic vertical centering of the string, but that's the whole source of the bug, so losing it is not so terrible.
It seems to be a bug in UILabel
. The same code works fine when UITextView
is used instead of UILabel
(UITextView
's default font size is different, so I tested it on different heights).
It really has nothing to do with the NSTextAttachment. It's that in iOS 7 as released so far, UILabel is not very good at drawing attributed strings. A simple attributed string with some underlining and a centered paragraph style will show up blank, or partially blank, in a UILabel; the same attributed string draws fine in a UITextView.
So, one solution for now is: Use UITextView instead. This is actually a pretty good solution because, in iOS 7, UITextView is just a wrapper around the Text Kit stack. So it is drawing the attributed string in a straightforward way. It is not hampered by the under-the-hood relationship to Web Kit that it had in previous iOS versions.
On the other hand, I have also found a workaround for this UILabel bug; you have to fiddle with the number of lines of the label and the string in such a way as to jam the text up to the top of the label: see my answer here - https://stackoverflow.com/a/19409962/341994
Or you could just wait for Apple to fix the bug and keep your fingers crossed. EDIT: In iOS 7.1, it appears that the bug will be fixed and no workaround will be needed.