首先,请打开你的微信朋友圈或者QQ空间,随便点一个评论按钮,看看是什么效果?
咦,键盘弹出来了诶!(废话!)
这不是重点,重点是屏幕自动滚动到了一个最合适的位置,对吗?(没试的赶紧去试一下)
怎么样,有没有很棒的感觉?
你天天都在用朋友圈或者空间,但你注意过这些细节吗?就算你注意到了,你想过这是怎么实现的吗?
尽管我从没想过。。。
但是今天师父让我去实现这样一个 tableView,然后加进公司的项目里。
ok,故事的背景和起因都交代完毕了,下面我们进入正题。
首先,在动手操作之前,我们应该想一些问题,比如说(只是举个例子):
1. 什么位置才是一个合适的位置?
2. tableView 怎么才能滚动到这个位置?
至少也要想这两点吧?
第一个问题很简单,就是刚好把点击的那个cell滚到键盘上方。
第二个问题,我个人最初的想法是,通过 contentOffset 改变 tableView 的位置。
那么我就需要知道我点击的 button 是属于哪个 cell 的。但是点击 button 时会触发 button 的响应事件方法,
而不会触发 didSelectRowAtIndexPath: 方法。(请自己试一试,多动动手)
于是就有了这篇文章的题目:点击 tableViewCell 里的 button 时如何确定是哪一个 cell ?
我们自定义一个 PTHomeTableViewCell ,继承自 UITableViewCell。
在PTHomeTableViewCell 中加入一个 button(即朋友圈和空间中的评论按钮),给 button 添加一个响应事件:
- (IBAction)showCommentInputView:(UIButton *)sender {
NSLog(@"showCommentInputView...");
}
点击评论按钮时就会调用这个方法,参数 sender 就是我们点击的那个 button。
但是我们怎么才能知道这个 button 是哪个 cell 里的呢?
其实很简单,我们来打印一下这个 button 的父类看看:
- (IBAction)showCommentInputView:(UIButton *)sender {
NSLog(@"showCommentInputView...");
UIView *view1 = [sender superview];
UIView *view2 = [view1 superview];
NSLog(@"=== %@ %@", [view1 class], [view2 class]);
}
输出结果如下图所示:
sender 的父类是 UITableViewCellContentView,
而 UITableViewCellContentView 的父类就是 PTHomeTableViewCell,也就是我们想要的!
接下来只需要这样:
NSIndexPath *indexPath = [(UITableView *)[[view2 superview] superview] indexPathForCell:view2];
NSLog(@"indexPath:--------%@", indexPath);
就能获取到这个 button 是哪行、哪个 section 的cell了!
完整代码如下:
- (IBAction)showCommentInputView:(UIButton *)sender {
NSLog(@"showCommentInputView...");
UIView *view1 = [sender superview];
UIView *view2 = [view1 superview];
NSLog(@"=== %@ %@ %@ %@", [view1 class], [view2 class], [[view2 superview] class], [[[view2 superview] superview] class]);
NSIndexPath *indexPath = [(UITableView *)[[view2 superview] superview] indexPathForCell:view2];
NSLog(@"indexPath:--------%@", indexPath);
}
总结一下:
cell 里的 button,它的 superview 是 UITableViewCellContentView,而它的 superview 就是我们自定义的 cell,cell 的 superview 是 UITableViewWrapperView,而它的 superview 就是我们的 UITableView 啦!
不过后来我发现想通过设置 contentOffset 来让 tableView 滚动到合适的位置太困难了,于是师父教了我另一个方法。
具体的下篇文章再说,自动滚动的 tableView 源码我已经传到 github 上了,欢迎 star
源码网址:https://github.com/963239327/AutoScrollTableView