0

I am setting some attributed text to textview, and giving line. I am trying to set baseline alignment vertically center but unable to set that. How can I set the text vertically center in textview.

Ash
  • 149
  • 2
  • 15

2 Answers2

2

First add/remove an observer for the contentSize key value of the UITextView when the view is appeared/disappeared:

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
}
Rahul Patel
  • 5,858
  • 6
  • 46
  • 72
-1

Try this,

UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Light" size:kFontSize]; // your font choice
NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:self.textView.text // text to be styled.
     attributes:@
     {
     NSFontAttributeName:font
     }];
NSMutableAttributedString *attrMut = [attributedText mutableCopy];
NSInteger strLength = attrMut.length;
NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
[style setLineSpacing:3]; // LINE SPACING
[style setAlignment:NSTextAlignmentCenter];
[attrMut addAttribute:NSParagraphStyleAttributeName
                value:style
                range:NSMakeRange(0, strLength)];

self.textView.attributedText = [attrMut copy];
Prabhu.Somasundaram
  • 1,380
  • 10
  • 13
  • NSMutableParagraphStyle helps in setting line spacing but the text will be aligned at the top. How can we align the text baseline vertically center? – Ash Feb 04 '16 at 08:19
  • No direct way. you can pad space in the beginning using NSString methods.calculate number of space based on your need. – Prabhu.Somasundaram Feb 04 '16 at 10:52