今天在做项目的时候,在 collectionView 的 cell 中添加了一个 textField,于是就出现了一个问题。
collectionView相关代码:
注册:
[_collectionregisterClass:[CollectionViewCellclass]forCellWithReuseIdentifier:@"cell"];
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionViewdequeueReusableCellWithReuseIdentifier:@"cell"forIndexPath:indexPath];
cell.backgroundColor = [UIColorcyanColor];
return cell;
}
cell 中添加的 textField
-(UITextField *)field{
if (!_field) {
_field = [[UITextFieldalloc]initWithFrame:CGRectMake(50, 50,250,50)];
_field.font =FONT(17);
_field.text =@"";
_field.textColor = [UIColorblackColor];
_field.backgroundColor = [UIColorlightGrayColor];
}
return_field;
}
在没有点击 textField 的时候,滑动页面不存在任何问题。但是当给 textField 输入内容或者点击这个 textField 后滑动页面,然后再滑动回当前页面,这时候 cell 就会消失不见。
原本以为这是cell的重用问题,经过长时间的调试,才发现是textField的问题。如果 textField 获得焦点,然后滑动 cell 那么 cell,就会消失不见。
解决办法是只需要在 collectionView 事件所在的文件中添加如下代码即可:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
[self.viewendEditing:YES];
}
这里顺便也说一下另外一个问题的解决办法,就是关于 cell 重用的问题。
很多时候我们在 cell 里面添加一些内容,当我们滑动后很多东西都会重复显示。我也同样遇到了这个问题,在 textField 中添加数据(按页滑动),滑动之后前面添加的数据会自动重复显示到后面页面中的 textField 中。
解决办法就是把 textField 中的值通过代理保存到一个可变数组中,然后通过 cell 显示。