2014-02-10 149 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

謝謝,爲我工作節省了我的時間 –