在UITextView中垂直居中对齐文本

时间:2016-02-02 09:33:04

标签: swift2 uitextview nsattributedstring

我正在为textview设置一些属性文本,并给出一行。我试图垂直居中设置基线对齐但无法设置。如何在textview中垂直居中设置文本。

2 个答案:

答案 0 :(得分:2)

首先在视图出现/消失时添加/删除contentSize UITextView键值的观察者:

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改变了内容偏移和插入的工作原理这个稍微修改过的解决方案现在需要设置内容插入的顶部而不是偏移量。

/// 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
}

答案 1 :(得分:0)

试试这个,

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