How to align text horizontally & vertically in UITextView? I want align text in UITextView with horizontal alignment & vertical alignment. Is there any custom way? Please help me out.....
This is a Swift solution and is different now since content insets and offsets have changed slightly. This solution works in Xcode 7 beta 6.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
textView.removeObserver(self, forKeyPath: "contentSize")
}
Apple has changed how content offsets and insets work this slightly modified solution is now required to set the top on the content inset instead of the offset.
/// Force the text in a UITextView to always center itself.
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
let textView = object as! UITextView
var topCorrect = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale) / 2
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
textView.contentInset.top = topCorrect
}
As far as I know there is no built in method for vertical alignment of a UITextView
. However, by updating the the contentOffset
you can get vertically centered text:
[textView setTextAlignment:NSTextAlignmentCenter];
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[textView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[textView removeObserver:self forKeyPath:@"contentSize"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
UITextView *tv = object;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With