2013-01-18 78 views
1

當我的UiTextView中添加了兩行或更多行時,它看起來不錯,但是當用戶只輸入一行時,文本停留在UiTextView的中間。我如何強制它停留在UiTextView的左上角?UiTextView - 僅添加一行時的位置

+0

檢查此博客[iOS:在UITextView中垂直對齊文本](http://imagineric.ericd.net/2011/03/10/ios-vertical-aligning-text -in-a-uitextview /),或者只是將'contentOffset'設置爲合適的值(零左右)。 – iDev

+0

你見過這個http://stackoverflow.com/questions/3760924/set-line-height-in-uitextview –

回答

1

你可以查看這個博客(iOS: Vertical aligning text in a UITextView),它解釋瞭如何做中心和底部垂直對齊。使用類似的邏輯並將contentOffset y參數設置爲零,以使其頂部對齊。

這是從博客的代碼,

- (void) viewDidLoad { 
    [textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL]; 
    [super viewDidLoad]; 
} 

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 
    UITextView *tv = object; 
    //Center vertical alignment 
    //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}; 

    //Bottom vertical alignment 
    CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height); 
    topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect); 
    tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect}; 
} 
+0

感謝您的幫助,但我只是找到了一個更簡單的解決方案。下一個代碼只會移動文本:'[textView setContentInset:UIEdgeInsetsMake(5,0,5,0)]' – Segev

+0

但是,即使設置了'contentInset',即使行數超過1,它也會設置正確嗎?我想我誤解了你的問題。 – iDev

+0

它將始終強制文本留在UITextView的右上角。當2行出現時,情況就是這樣,但由於某種原因,只有一行文本被居中。 'ContentInset'修復了這個問題。 – Segev

1

我只是找到了一個更簡單的解決方案。下一個代碼將移動文本:[textView setContentInset:UIEdgeInsetsMake(5, 0, 5,0)]