集合视图中的第一个项目未预先选择

时间:2017-09-04 17:55:45

标签: ios objective-c uicollectionviewcell

我正在尝试在加载时预先选择第一个集合视图单元格但是在加载时未预先选择项目

用于预选集合视图单元格的代码在下面提供

MenuBar.m // Type  UIView <UICollectionViewDelegate ,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {

...

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];

....
  // below code in   -(instancetype)initWithFrame:(CGRect)frame

 NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];

    [collectionView selectItemAtIndexPath:selectedIndexPath
                                 animated:false
                           scrollPosition:UICollectionViewScrollPositionNone];




....
// below code in   -(instancetype)initWithFrame:(CGRect)frame
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

}

2 个答案:

答案 0 :(得分:0)

在您的课程中实施此方法collectionView:didSelectItemAtIndexPath

预选是应该由UIViewController控制的一部分逻辑 提供预选自定义视图的方法: .h档案:

- (void)preselectCellAt:(NSIndexPath *)indexPath;

您的.m文件:

- (void)preselectCellAt:(NSIndexPath *)indexPath {
       [collectionView selectItemAtIndexPath:indexPath
                                     animated:false 
                     scrollPosition:UICollectionViewScrollPositionNone];
      [self collectionView:collectionView didSelectItemAtIndexPath:indexPath]; 
    }

初始化ViewController的超级视图UIView

- (Void)viewDidiAppear {
  [super viewDidiAppear];
  NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
  [self.customView preselectCellAt:selectedIndexPath];
}

答案 1 :(得分:0)

您必须在selectedBackgroundView中设置UICollectionViewCell

例如,如果您希望UICollectionViewCell在选中时为绿色,则必须在UICollectionViewCell类中编写此类代码

Objcective C

- (void)awakeFromNib() {
    [super awakeFromNib];

    UIView *selectedView = [[UIView alloc] initWithFrame: [self bounds]];
    [selectedView setBackgroundColor: [UIColor greenColor]];

    [self setSelectedBackgroundView: selectedView];
}

<强>夫特

override func awakeFromNib() {
    super.awakeFromNib()

    let selectedView = UIView(frame: self.bounds)
    selectedView.backgroundColor = .green

    self.selectedBackgroundView = selectedView
}

或者您可以直接从ViewController collectionView:cellForItemAt方法

中定义它

<强> UPD

正如Yerkebulan Abildin所提到的,只有从笔尖创建UICollectionViewCell时,此代码才有效。如果您是通过代码创建的,则可以在selectedBackgroundView方法中定义init(因为awakeFromNib不会打电话)