Aligning text vertically center in UITextView

為{幸葍}努か 提交于 2020-01-17 04:47:07

问题


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.


回答1:


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
}



回答2:


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];


来源:https://stackoverflow.com/questions/35149587/aligning-text-vertically-center-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!