UICollectionView点击效果-松开手选中颜色消失

当我们使用集合视图UITableView、UICollectionView时,往往需要给UITableViewCell 、UICollectionViewCell的点击事件加一个跟UIButton一样的高亮效果,否则用户会觉得其实自己压根没点中一样,这样无形之中便降低了用户体验。

像这种效果:

highlight.gif

UITableView

先说UITableView,我们应该有遇到过,在点击cell得时候,默认会有一个选中状态的背景颜色,一般是灰色的,当我们松开手选中颜色会立即消失

代码如下:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 松开手选中颜色消失
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

UICollectionView

UICollectionView的item点击效果需要自己实现,系统提供了这些方法

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
   //当cell高亮时返回是否高亮
    return YES;
}
 
- (void)collectionView:(UICollectionView *)colView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath];
    //设置(Highlight)高亮下的颜色
    [cell setBackgroundColor:[UIColor grayColor]];
}
 
- (void)collectionView:(UICollectionView *)colView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath];
    //设置(Nomal)正常状态下的颜色
    [cell setBackgroundColor:[UIColor whiteColor]];
}

实现这两个方法后会发现单击并没有看到效果,只有长按才能看到颜色变化。要实现单击就能看到点击效果需设置UICollectionView的delaysContentTouches属性为false。


self.collectionView.delaysContentTouches = false;

  • 另外我尝试调用了这个方法,没有看到高亮,目前使用上面说的方法
// UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    /* 取消单元格当前选中状态 */
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。