本文属 iOS小经验系列:累积平时看起来简单,容易忽视的边边角角,各路大佬敬请回避。
一个表格视图(或者宫格视图)中,当一个单元格被选中时设置彩色样式,选中其它单元格时设置灰色样式。
通过实现选中和非选择的代理,以在适当的时机进行UI更新操作。
//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
//非选中
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
执行方法的主体:tableview对象
//选中
- (void)selectRowAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;
//非选中
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;
注意的是:
UITableViewSelectionDidChangeNotification
。- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
代理方法,你就有机会还原cell的默认样式。执行方法的主体:cell对象
- (void)setSelected:(BOOL)selected animated:(BOOL)animated; // animate between regular and selected state
注意的是:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath;
的非选中代理方法,你也就没有机会还原cell的默认样式。//选中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
//非选中
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
执行方法的主体:UICollectionView对象
//选中
- (void)selectItemAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition;
//非选中
- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;
注意的是:
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
代理方法,你就有机会还原cell的默认样式。执行方法的主体:cell对象
- (void)setSelected:(BOOL)selected;
注意的是:
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath ;
代理方法。比如,下面两种方案
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
[cell setSelected:YES];
上述方案仅仅改变cell的属性,但当屏幕点击选中其它cell的时候,也不会执行原cell的非选中代理。
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
上述方案改变了cell的属性,而且当选中其它cell的时候,会执行非选中代理。
didDeselect
方法,一个不执行。didSelect
方法的。如果你真的想在改变选中状态的时候执行didSelect
代理,那么可以手动执行:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[mytableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
if ([mytableview.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
[mytableview.delegate tableView:mytableview didSelectRowAtIndexPath:indexPath];
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有