UIScrollView的滚动事件和滚动到指定位置这两种方法经常有使用到,这里做一个笔记,记录一下我在开发中常用的这两个事件,首先需要实现UIScrollViewDelegate代理,如下。
@interface ChatViewController ()<BackButtonHandlerProtocol> @end
使用一:我们需要在UITableview中滚动来隐藏键盘的编辑状态,可以实现scrollViewWillBeginDragging的代理方法,当然了,你也可以做很多别的操作。
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [UIView animateWithDuration:0.5 animations:^{ //带动画的隐藏键盘编辑状态 [[[UIApplication sharedApplication] keyWindow] endEditing:YES]; }]; }
使用二:在uitableview中使用UIScrollview滚动到指定的位置有点复杂,不过有下面这个案例你就能够轻松实现了,这里是滚动到最uitableview最后一行
//自定义方法 - (void)scrollToBottomisAnimated:(BOOL)isAnimated { //dataSource是列表数组 if (self.dataSource.count == 0) { return; } double delayInSeconds = 0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //需要滚动到的位置,最后一行 NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0]; [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:isAnimated]; }); }
其中的atScrollPosition是一个枚举类型,表示的是uitableview的cell滚动到的边缘位置。