Last active
August 11, 2018 13:15
-
-
Save acalism/11ed8c865d4f58df8494ee999598490c to your computer and use it in GitHub Desktop.
Pitfall in Calculating a line-limited textView's size
This file contains 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
textView.attributedText = originalContent | |
let lineLimit = 5 | |
textView.isEditable = true | |
textView.isScrollEnabled = false | |
// eliminate inner paddings, when right is minus number, it seems useless. | |
// textView.contentInset = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0) | |
textView.textContainer.lineFragmentPadding = 0; // better way | |
textView.textContainerInset = .zero // default is (8, 0, 8, 0) | |
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition | |
textView.textContainer.lineBreakMode = .byTruncatingTail | |
// two incomplete methods, which do NOT work in iOS 8.3 | |
// size.width可能比maxSize.width小 ————遗憾的是 iOS 8.3 上此方法无视maximumNumberOfLines参数,所以得借助于UILabel | |
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines | |
// let size = textView.sizeThatFits(maxSize) | |
// 遗憾的是 iOS 8.3 上此方法失效了,得借助于UILabel | |
// Does not work in iOS 8.3 | |
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size | |
// Suggested method: use a temperary label to get its size | |
let label = UILabel(); label.attributedText = originalContent | |
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size | |
textView.frame.size = size |
to eliminate paddings:
textView.textContainer.lineFragmentPadding = 0 // default value is 5.0
textView.textContainerInset = .zero // default value is {0, 8, 0, 8}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As you see, iOS 8.3 is a monster with textView.