Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active August 11, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalism/11ed8c865d4f58df8494ee999598490c to your computer and use it in GitHub Desktop.
Save acalism/11ed8c865d4f58df8494ee999598490c to your computer and use it in GitHub Desktop.
Pitfall in Calculating a line-limited textView's size
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
@acalism
Copy link
Author

acalism commented Nov 7, 2017

As you see, iOS 8.3 is a monster with textView.

@acalism
Copy link
Author

acalism commented Aug 11, 2018

to eliminate paddings:
textView.textContainer.lineFragmentPadding = 0 // default value is 5.0
textView.textContainerInset = .zero // default value is {0, 8, 0, 8}

@acalism
Copy link
Author

acalism commented Aug 11, 2018

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