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

时间:2014-02-10 05:25:34

标签: ios uitextview

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

4 个答案:

答案 0 :(得分: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")
}

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 :(得分:7)

据我所知,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};
}

答案 2 :(得分:5)

将中间与Swift垂直对齐:

在viewDidLoad中:

textField.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)

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

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)

}

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

答案 3 :(得分:0)

当你想要改变水平和垂直对齐时,你应该提供你想做什么的背景,

UITextview有一个容器和一个框架属性,您可以与另一个UITextview / Imageview等对齐.frame属性有一个原点和一个大小,您可以修改它以对齐您的视图。

UITextview中的文本有一个名为textalignment的属性,你可以设置为NSTextAlignmentLeft,NSTextAlignmentJustified,如你所知,你也可以调整容器的内容偏移属性,但我发现调整框架更直接。

相关问题