Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Last active January 6, 2019 23:37
Show Gist options
  • Save samuelbeek/d43e1d512fd0b2261fdd to your computer and use it in GitHub Desktop.
Save samuelbeek/d43e1d512fd0b2261fdd to your computer and use it in GitHub Desktop.
Vertically aligned text in textview
class VerticalCenteredTextView: UITextView {
override init(frame: CGRect) {
super.init(frame: frame)
addContentSizeObserver()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addContentSizeObserver() {
self.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
private func removeContentSizeObserver() {
self.removeObserver(self, forKeyPath: "contentSize")
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
var top = (bounds.size.height - contentSize.height * zoomScale) / 2.0
top = top < 0.0 ? 0.0 : top
object.setContentOffset(CGPoint(x: contentOffset.x, y: -top), animated: false)
}
deinit {
removeContentSizeObserver()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment