Last active
January 6, 2019 23:37
-
-
Save samuelbeek/d43e1d512fd0b2261fdd to your computer and use it in GitHub Desktop.
Vertically aligned text in textview
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 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