2014-02-10 134 views

回答

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}; 
} 
+0

此代码去哪? (ViewController.m?) – Cindeselia

+0

@Cindeselia代码当前编写的方式,您需要将其添加到您的文本视图所在的位置。 – Gad

+0

请注意,如果文本视图的“Selectable”标志被选中 – Maiaux

0

当你想改变水平和垂直对齐你应该提供你的意思的情况下做的,

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

UITextview中的文本有一个名为textalignment的属性,您可以将它设置为NSTextAlignmentLeft,NSTextAlignmentJustified,如上所示,您也可以调整容器的内容偏移属性,但我发现调整框架更直截了当。

-4
self.qtyField.textAlignment = NSTextAlignmentCenter; 
5

垂直对齐中间用斯威夫特:

在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) 

} 

其中文本字段被连入实际在您的视图中的文本字段。

+0

可以正常工作,但不知何故它不适用于unwind segue,那么更改contentOffset似乎只能工作......任何想法为什么? – SKYnine

24

这是一个Swift解决方案,现在不同了,因为内容插入和偏移量稍微有所变化。 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") 
} 

苹果改变内容的偏移和插图是如何工作的,现在这个稍微修改的方案需要设置的内容插入的代替偏移顶部此方法适用于在Xcode 7测试版。

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

这对我来说很适合IOS 9/Swift 2谢谢! – Kitson

+0

真棒..为我工作。浪费了近2个小时。 –

+0

谢谢,为我工作节省了我的时间 –