2017-09-04 37 views
0

我试图预选上负载的第一集合观察室,但项目没有预选负载我用来预选集合观察室第一项没有预选

代码如下

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 
{ 

} 
+0

为什么要调用collectionView:didSelectItemAtIndexPath?你在班上实施了这个方法吗? –

回答

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]; 
} 
+0

谢谢你的回复。 UICollectionView定义的类的类型是UIView。当我添加上面的代码时,我得到错误。错误是'不可见@interface for'UIView'声明选择器'viewDidAppear:'' – ios

+0

用willMoveToSuperview替换的方法 –

+0

仍然有相同的错误 – ios

0

你必须设置selectedBackgroundViewUICollectionViewCell

例如,如果你希望你的UICollectionViewCell是绿色选择的时候,你有你的UICollectionViewCell类写这样的代码

ObjcectiveÇ

- (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 
} 

或者你可以直接从哟乌尔ViewControllercollectionView:cellForItemAt方法

UPD

由于Yerkebulan Abildin已经提到的,这个代码将只有当你创建你UICollectionViewCell从笔尖工作。如果从代码创建它,则可以在init方法中定义selectedBackgroundView方法(因为awakeFromNib不会调用)

+0

awakeFromNib将无法正常工作 –