-
-
Save ergunkocak/ef1d41b5d08aaf8bf470c5fed1cce5c1 to your computer and use it in GitHub Desktop.
A UILabel subclass that detects and attempts to fix intrinsicContentSize bugs in UILabel on iOS 11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
/// A UILabel subclass that detects and attempts to fix intrinsicContentSize bugs in UILabel | |
class iOS11CompatibleLabel: UILabel { | |
override var intrinsicContentSize: CGSize { | |
// First attempt at a fix... | |
// All UILabels that misbehave have numberOfLines==0 and preferredMaxLayoutWidth=0 | |
// but all UILabels that have these two properties as 0 do not necessarily misbehave | |
// So this fix worked, but modified the label unecessarily some of the time | |
// Note that on subsequent passes, UIKit sets preferredMaxLayoutWidth to a non-zero value, presumably to iterate onto the correct height for the label. | |
// let shouldAdjustNumberOfLines = self.label.numberOfLines == 0 && self.label.preferredMaxLayoutWidth == 0 | |
// Second attempt at a fix... | |
// This is a little more hacky but doesn't have any false positives as the above attempt does | |
guard super.intrinsicContentSize.width > 1000000000.0 else { | |
return super.intrinsicContentSize | |
} | |
var count = 0 | |
if let text = self.text { | |
text.enumerateLines {(_, _) in | |
count += 1 | |
} | |
} else { | |
count = 1 | |
} | |
let oldNumberOfLines = self.numberOfLines | |
self.numberOfLines = count | |
let size = super.intrinsicContentSize | |
self.numberOfLines = oldNumberOfLines | |
return size | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment