2013-04-18 104 views
2

我有一個UITextView裏面的UIScrollView需要自動滾動,一旦用戶開始編輯它。這是因爲鍵盤會覆蓋textview。UIScrollView以編程方式滾動

這裏是代碼 -

viewDidLoad:

feedBackformView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, segmentedControl.frame.origin.x + self.segmentedControl.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)]; 
feedBackformView.backgroundColor = [UIColor whiteColor]; 
feedBackformView.scrollEnabled = YES; 
feedBackformView.delegate = self; 
feedBackformView.userInteractionEnabled = YES; 
feedBackformView.showsVerticalScrollIndicator = YES; 
feedBackformView.contentSize = CGSizeMake(320, 700); 

commentsView = [[UITextView alloc] initWithFrame:CGRectMake(5, emailField.frame.origin.y + 40, 250, 150)]; 
commentsView.delegate = self; 
commentsView.layer.borderWidth = 2.0f; 
commentsView.layer.cornerRadius = 5; 

和這裏的委託方法實現 -

-(void)textViewDidBeginEditing:(UITextView *)textView{ 
    CGPoint point = textView.frame.origin; 
    [scrollView setContentOffset:point animated:YES]; 
} 

然而,沒有任何反應。

+0

當您嘗試使用scrollRectToVisible進行滾動時會發生什麼情況。 – guenis

回答

4

你做得很好,但使用的feedBackformView代替滾動視圖,同時設定內容textViewDidBeginEditing:方法抵消,只是有TextView的DelegateMethod下面的代碼

feedBackformView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, 320, 200)]; 
feedBackformView.backgroundColor = [UIColor whiteColor]; 
feedBackformView.scrollEnabled = YES; 
feedBackformView.delegate = self; 
feedBackformView.userInteractionEnabled = YES; 
feedBackformView.showsVerticalScrollIndicator = YES; 
feedBackformView.contentSize = CGSizeMake(320, 700); 

commentsView = [[UITextView alloc] initWithFrame:CGRectMake(5, 40, 250, 150)]; 
commentsView.delegate = self; 
commentsView.layer.borderWidth = 2.0f; 
commentsView.layer.cornerRadius = 5; 

[feedBackformView addSubview:commentsView]; 
[self.view addSubview:feedBackformView]; 

一看,

-(void)textViewDidBeginEditing:(UITextView *)textView{ 
    CGPoint point = textView.frame.origin; 
    [feedBackformView setContentOffset:point animated:YES]; 
} 

希望它能幫你...

+0

像一個魅力工作。謝謝 –

1

您可以使用滾動視圖scrollRectToVisible:animated或這裏所描述的方法setContentOffset:animatedUIScrollView Class Reference

記住的UITextView都有自己的滾動視圖。所以你可能不需要將它嵌套在另一個滾動視圖中。但是如果你的應用有趣,你可能需要。

1

您是否已經在可見點滾動?

-(void)textViewDidBeginEditing:(UITextView *)textView{ 
    // try this instead 
    CGPoint point = CGPointMake(textView.frame.origin.x, 
           textView.frame.origin.y + textView.frame.size.height); 
    [scrollView setContentOffset:point animated:YES]; 

    // What does this produce? 
    NSLog(@"%@ %@", NSStringFromCGPoint(scrollView.contentOffset), 
        NSStringFromCGRect(textView.frame)); 
}