Skip to content

Instantly share code, notes, and snippets.

@a2
Created July 14, 2018 18:59
Show Gist options
  • Save a2/1cd7ba18fd43de93d56d306d1f1b3df5 to your computer and use it in GitHub Desktop.
Save a2/1cd7ba18fd43de93d56d306d1f1b3df5 to your computer and use it in GitHub Desktop.
Workaround for rdar://42199059
extension NSLayoutManager {
func invalidateLayout() {
let characterRange: NSRange
if let textStorage = textStorage {
// fast path
characterRange = NSRange(0 ..< textStorage.length)
} else {
characterRange = self.characterRange(forGlyphRange: NSRange(0 ..< numberOfGlyphs), actualGlyphRange: nil)
}
invalidateLayout(forCharacterRange: characterRange, actualCharacterRange: nil)
}
}
extension UIView {
var readableContentMargins: UIEdgeInsets {
let guide = readableContentGuide
guard let owningView = guide.owningView else {
return .zero
}
let readableFrame = guide.layoutFrame
return UIEdgeInsets(
top: readableFrame.minY,
left: readableFrame.minX,
bottom: owningView.bounds.maxY - readableFrame.maxY,
right: owningView.bounds.maxX - readableFrame.maxX
)
}
}
// Called from `viewLayoutMarginsDidChange()` on iOS 11+ -- otherwise viewDidLayoutSubviews()
func updateContentInset() {
if let textView = textView {
let margins = view.readableContentMargins
textView.contentInset = UIEdgeInsets(top: 0, left: margins.left, bottom: 0, right: margins.right)
textView.layoutManager.invalidateLayout()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment