Last active
August 29, 2015 14:19
-
-
Save samuelbeek/d058cadf41ddd0b5aab7 to your computer and use it in GitHub Desktop.
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
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