iOS UITableView 和 UICollectionView 设置默认选中状态

来源:互联网 发布:python 改变路径 编辑:程序博客网 时间:2024/05/18 17:00

使用场景:进入页面时,就让某一行(单元)处于默认选中状态。
以UITableView 为例:
关键 API:

- (void)selectRowAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;- - (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;

// Selects and deselects rows. These methods will not call the delegate methods (-tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath:), nor will it send out a notification.
// 选中或者不选中某一行。都不会回调tableview的代理方法,如:(
-tableView:willSelectRowAtIndexPath:
or tableView:didSelectRowAtIndexPath:),同时也不会发送 (UITableViewSelectionDidChangeNotification)这个通知。
所以,代理不起作用,通知也不起作用。但可以使用 设置选中状态这个方法。
使用方法:
重要:一定要等数据也加载完成之后,再调用!!!
获取到想要显示的cell 的indexPath,然后在初始化好TableView 并切 数据加载完成之后,调用
方法
- (void)selectRowAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;。

但,这个时候的cell 还是不会处于选中状态,还要手动设置下。我用属性设置发现没有效果,然后用set方法发现有效果。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated; // animate between regular and selected state

这个时候选中的indexPath 就是你想要默认选中的了。
eg:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:selectIndex inSection:0];    [tab selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; //  设置默认选中的行UITableViewCell *cell = [tab cellForRowAtIndexPath:indexPath];    [cell setSelected:YES animated:YES];  // 使cell 的 状态设置为选中状态

同理,UICollectionView 的API中也有这样的方法。但跟UITableView 略有不同的是,UICollectionViewCell 没有- (void)setSelected:(BOOL)selected animated:(BOOL)animated; 这个方法,测试发现,不需要这个setSelected:方法就可以使item处于选中状态。只需要在数据加载完成之后调用selectItemAtIndexPath:这个方法就可以了。
API:

- (void)selectItemAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition;- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;- 

eg:

    [collect selectItemAtIndexPath:[NSIndexPath indexPathForItem:2 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
0 1
原创粉丝点击