Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Last active August 29, 2015 14:19
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 samuelbeek/d058cadf41ddd0b5aab7 to your computer and use it in GitHub Desktop.
Save samuelbeek/d058cadf41ddd0b5aab7 to your computer and use it in GitHub Desktop.
class TextView: 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
contentOffset = CGPoint(x: contentOffset.x, y: -top)
}
deinit {
removeContentSizeObserver()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment