1

iOS 中的标准手势之一是,通过点击状态栏(屏幕顶部的状态栏,显示您的信号级别、电池强度等),将自动滚动任何内容(例如,在表格视图、滚动视图中)等)到顶部。

我正在编写一个与聊天服务器交互的应用程序。当收到新的聊天消息时,它们会被添加到 UITextView 的底部。用户当然可以回滚查看以前的聊天记录。

是否可以覆盖“点击状态栏”快捷方式,而不是滚动到顶部,而是可以调用我自己的方法之一?(我的视图控制器中有一个方法可以自动将聊天窗口滚动到底部)。

4

2 回答 2

2

这就是我想出的。关键是覆盖scrollViewShouldScrollToTop:方法。并返回 NO 以防止默认行为。
要注意的一件事是,scrollViewShouldScrollToTop:如果滚动视图的内容已经在滚动视图的顶部,则不会调用它。请参阅下面代码中的技巧。

@interface ViewController ()
<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width,
                                             self.view.bounds.size.height * 2);

    // if the scrollView contentOffset is at the top
    // (0, 0) it won't call scrollViewShouldScrollToTop
    self.scrollView.contentOffset = CGPointMake(0, 1);
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    // call your custom method and return YES
    [self scrollToBottom:scrollView];
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // be sure that when you are at the top
    // the contentOffset.y = 1
    if (scrollView.contentOffset.y == 0)
    {
        scrollView.contentOffset = CGPointMake(0, 1);
    }
}

- (void)scrollToBottom:(UIScrollView *)scrollView
{
    // do whatever you want in your custom method.
    // here it scrolls to the bottom
    CGRect visibleRect = CGRectMake(0, scrollView.contentSize.height - 5, 1, 1);
    [scrollView scrollRectToVisible:visibleRect animated:YES];
}

@end
于 2012-10-11T20:14:30.737 回答
0

Try this:

- (void)myMethod {

    [myScrollableObject setScrollsToTop:NO];
}

Any object inheriting UIScrollView should have this property.

Reference

于 2012-10-11T19:51:48.590 回答