美文网首页
UICollectionView <一> 选中Cel

UICollectionView <一> 选中Cel

作者: erbai | 来源:发表于2016-10-27 17:46 被阅读2989次

UICollectionView 是最常用的控件,UITableView也是定制过的UICOllectionView。所以说,拓展度是最高的,很多UITableView中的效果在UICollectionView中没有特定的属性,比如选中效果。

tableView选中效果设置

tableview中,选中效果可以通过设置属性来是实现。

@property(nonatomic) UITableViewCellSelectionStyle selectionStyle

typedef enum : NSInteger {
   UITableViewCellSelectionStyleNone, // 无选中效果
   UITableViewCellSelectionStyleBlue, // 蓝色选中效果 
   UITableViewCellSelectionStyleGray, // 灰色选中效果
   UITableViewCellSelectionStyleDefault // 没试验过的选中效果
}  UITableViewCellSelectionStyle;

如果想要点击选中,松手取消选中的状态,在点击的代理方法中调用
- deselectRowAtIndxPath:animated: 方法即可。

collectionView选中效果

上面说到tableView是collectionView的定制,所以collectionView也是有选中方法设置的。

// 返回 YES 允许显示高亮 NO 不允许显示高亮状态
- (BOOL)collectionView:(UICollectionView **) collectionView 
shouldHighlightItemAtIndexPath:(NSIndexPath *)*indexPath*
// 设置点击时 触发的高亮状态方法,可在此代理方法中进行高亮状态的处理。例如高亮颜色的变换。
- (void)collectionView : (UICollectionView *)*collectionView* 
didHighlightItemAtIndexPath : (NSIndexPath *)*indexPath*
// 设置点击结束时(即点击后松开状态)触发。
- (void)collectionView:(UICollectionView *)*collectionView* 
didUnhighlightItemAtIndexPath : (NSIndexPath *)*indexPath*

当我们想改变cell点击和松开的颜色时,可以修改 cell的 backgroundColor属性。设置cell的背景色使用contentView.backgroundColor
区别:backgroundColor是UIView的方法。就是承载cell的view。
contentView.backgroundColor是cell视图的颜色

我猜测当点击事件触发的时候,会把cell的contentVeiw的颜色清空,这样才会显示在最底层的View的颜色,即view的颜色。

通过上面介绍的代理方法和属性,即可自定义设置点击collectionView的点击颜色了。

注意事项:

在实际开发中,为了让点击效果出现后消失,我们都会使用以下两种方法
- (void)collectionView : (UICollectionView *)collectionView
didSelectItemAtIndexPath : (NSIndexPath *)indexPath
- (void)collectionView : (UICollectionView *)collectionView
didDeselectItemAtIndexPath : (NSIndexPath *)indexPath

在点击的代理方法中调用取消点击方法。
然而如果你实现了 本文介绍的 这个两个方法改变选中颜色,你会发现只有长按时才会看到设置的颜色。
原因:长按没有松手的时候,触发的是高亮方法,松手触发的是取消高亮的方法。轻触点击的时候会很快速的响应 高亮和取消高亮的方法,所以看不到颜色的改变。此时,需要设置delaysContentTouches属性为NO,此时当点击的时候会立刻调用点击事件的begin方法,率先变成高亮状态。

@property(nonatomic) BOOL delaysContentTouches; // default is YES. if NO, 
//we immediately call -touchesShouldBegin:withEvent:inContentView:. 
//this has no effect on presses

本文涉及重要的相关API:

UITableView
@property(nonatomic) UITableViewCellSelectionStyle selectionStyle
UICollectionView
@property(nonatomic) BOOL delaysContentTouches
- (BOOL)collectionView:(UICollectionView ) collectionView
shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
- (void)collectionView : (UICollectionView )collectionView
didHighlightItemAtIndexPath : (NSIndexPath )indexPath
-(void)collectionView:(UICollectionView )collectionView
didUnhighlightItemAtIndexPath : (NSIndexPath )indexPath

相关文章

网友评论

      本文标题:UICollectionView <一> 选中Cel

      本文链接:https://www.haomeiwen.com/subject/jfqsuttx.html