UIScrollView以编程方式滚动

时间:2013-04-18 01:28:19

标签: ios objective-c uiscrollview uitextview uitextviewdelegate

我在UIScrollView中有一个UITextView,需要在用户开始编辑后自动滚动。这是因为键盘将覆盖文本视图。

这是代码 -

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];
}

然而,没有任何反应。

3 个答案:

答案 0 :(得分:4)

你做得很好但是使用 feedBackformView 而不是 scrollView ,而在textViewDidBeginEditing:方法中设置内容偏移量,只需查看下面的代码

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];

在textview DelegateMethod中,

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

希望它会让你感到高兴......

答案 1 :(得分:1)

您可以使用scrollView scrollRectToVisible:animated或此处描述的setContentOffset:animated方法: UIScrollView Class Reference

请记住,UITextView带有自己的滚动视图。所以你可能不需要将它嵌套在另一个scrollview中。但是如果你的应用程序很有趣,你可能需要这样做。

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