AliSoftware / OHAttributedLabel

UILabel that supports NSAttributedString
https://github.com/AliSoftware/OHAttributedLabel/wiki
1.51k stars 344 forks source link

OHAttributedLabel doesn't work with autolayout #171

Open twobitlabs opened 10 years ago

twobitlabs commented 10 years ago

If you create an OHAttributedLabel without a frame and position it using autolayout, it has 0 height. This is because when intrinsicContentSize is invoked, attributedText is not set in the UILabel superclass, so the label appears to be empty. Setting the attributedText on the UILabel superclass allows it to calculate the intrinsicContentSize, without any apparent side effects.

AliSoftware commented 10 years ago

We can't do that because this property is only present since iOS6 and OHAttributedLabel is intended specifically to support attributed strings for projects that have to support pre-iOS6 projects (that's why it has been created, at the time UILabel didn't support NSAttributedStrings directly yet). If you use UILabel on iOS6+ better use directly iOS' NSAttributedLabel support directly by UILabel. If you need attributed string support for pre-iOS6, OHAttributedLabel is what you need but then we obviously can't use any property that did not exist until iOS6.

The issue is still open as there is probably a real issue with AutoLayout but I can't accept your pull request as a solution. Maybe better call setNeedsUpdateConstraints or something similar instead to force AutoLayout to recompute the intrisicContentSize when we change the attributedString property, or implement/override intrisicContentSize ourselves to return the sizeThatFits:{CGFLOAT_MAX, CGFLOAT_MAX} or something similar? In any case we need to call those conditionally, checking if the method exists before trying to call it, as usual in such cross-SDK development case.

twobitlabs commented 10 years ago

We're mainly using OHAttributedLabel in iOS6+ to render tweets with links, so the user can tap a #hashtag or @mention and go directly to the appropriate URL.

I'll take another look at intrinsicContentSize. I'd tried just calling [super setAttributedText:_attributedText] inside intrinsicContentSize (which is also iOS6+), then calling [super intrinsicContentSize], but was getting errors like [__NSCFType lineBreakMode]: unrecognized selector.

I think the right approach is just to have OHAttributedLabel calculate the appropriate content size. I'll do some more digging.

AliSoftware commented 10 years ago

At least encapsulate the calls to methods introduced in iOS6 like setAttributedtext: and all those inside a respondsToSelector: test to make it safe against previous SDKs and be sure to respect Apple's cross-SDK guidelines.