Skip to content

Instantly share code, notes, and snippets.

@samskiter
Last active April 1, 2021 15:59
Show Gist options
  • Save samskiter/8f420d37b9a6bb6b3c6639e016698ece to your computer and use it in GitHub Desktop.
Save samskiter/8f420d37b9a6bb6b3c6639e016698ece 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
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
}
}
@ergunkocak
Copy link

You are just a life saver after 6 hours of struggle. Thank you very very much

@samskiter
Copy link
Author

No worries! Just a headsup - I think we had to reduce from 1000000000.0 at some point (a newer version of iOS seemed to use a lower number)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment