Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text horizontally & vertically in UITextView? [duplicate]

Tags:

ios

uitextview

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.....

like image 462
JKMania Avatar asked Feb 10 '14 05:02

JKMania


2 Answers

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
}
like image 50
Hamer Avatar answered Oct 28 '22 13:10

Hamer


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};
}
like image 28
Gad Avatar answered Oct 28 '22 11:10

Gad