如何在UITextView中水平和垂直对齐文本?

JKM*_*nia 5 uitextview ios

如何在UITextView中水平和垂直对齐文本?我希望UITextView中的文本与水平对齐和垂直对齐对齐.有没有自定义方式?请帮我.....

Ham*_*mer 26

这是一个Swift解决方案,现在不同了,因为内容插入和偏移略有变化.此解决方案适用于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")
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

  • 不在Xcode 8工作.有没有人有任何想法如何做到这一点? (2认同)

Gad*_*Gad 7

据我所知,没有内置的方法来垂直对齐a UITextView.但是,通过更新,contentOffset您可以获得垂直居中的文本:

[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};
}
Run Code Online (Sandbox Code Playgroud)


max*_*mzd 5

将中间部分与Swift垂直对齐:

在viewDidLoad中:

textField.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
Run Code Online (Sandbox Code Playgroud)

然后在视图控制器中的其他位置:

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {

    var topCorrect : CGFloat = (textField.frame.height - textField.contentSize.height);
    topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect / 2
    textField.contentOffset = CGPoint(x: 0, y: -topCorrect)

}
Run Code Online (Sandbox Code Playgroud)

其中textField连接到视图中的实际文本字段.