您的位置:首页 > 其它

Collectionview学习(三)利用故事版动态改变cell内容展示实战demo

2017-03-27 10:35 465 查看
使用storyboard过程中遇到问题报错:the xxx outlet from xxx to the xxx is invalid. Outlet can't be connected to repeating content.

错误原因:在storyboar中自定义了cell,但是却在viewcontroller中索引了iboutlet 的cell内容。cell本身是不属于viewcontroller的,所以会报错。

解决方法:自定义cell,将iboutlet声明在自定义的cell中去。注意应当首先去除掉问题iboutlet之前的旧关联



因为当前的demo使用的是故事版的方式,在storyboard中已经设置了cell identifier,并且将cell的class设置为了自定义的cell名称。所以就不需要再次registerclass的操作了,否则会覆盖掉之前的cell而出错。

那么如果来达到访问故事版中的cell内容并且修改其内容呢?很简单,只要在对应的datasrouce方法中把创建的cell的类定义成自定义的类,并且在自定义的cell类中公开对应的接口就可以了。代码如下:

#import
<UIKit/UIKit.h>
@interface CustomCollectionviewCellCollectionViewCell :
UICollectionViewCell
@property (nonatomic,
strong)
IBOutlet
UILabel
*backgroundLabel;
@property (nonatomic,
strong)
IBOutlet
UIImage*backgroundImageView;
- (void)changeLabelBackgroundColor;
- (void)setTabelText:(NSString *)text;
@end

#import
"CustomCollectionviewCellCollectionViewCell.h"
@implementation CustomCollectionviewCellCollectionViewCell
- (void)changeLabelBackgroundColor {
   self.backgroundLabel.backgroundColor = [UIColor greenColor];
- (void)setTabelText:(NSString
*)text {
   
self.backgroundLabel.text = text;
@end

#import
"CustomCollectionView.h"
#import
"CustomCollectionviewCellCollectionViewCell.h"
#define COLLECTIONVIEW_CELL_IDENTIFIER          @"CollectionviewCellIdentifier"
@interface
CustomCollectionView ()
@property (nonatomic,
strong) IBOutlet
UICollectionView *collectionView;
@end
@implementation CustomCollectionView
- (void)viewDidLoad {
    [super
viewDidLoad];
}
- (void)didReceiveMemoryWarning {
    [super
didReceiveMemoryWarning];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   
return 10;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
   
return 1;
}
- (CustomCollectionviewCellCollectionViewCell
*)collectionView:(UICollectionView *)viewCollection cellForItemAtIndexPath:(nonnull
NSIndexPath *)indexPath {
   
CustomCollectionviewCellCollectionViewCell *cell = [viewCollection
dequeueReusableCellWithReuseIdentifier:COLLECTIONVIEW_CELL_IDENTIFIER
forIndexPath:indexPath];
    [cell
changeLabelBackgroundColor];
    [cell
setTabelText:[NSString
stringWithFormat:@"%@%ld",
@"Label", indexPath.row]];
   
return cell;
}
最终的效果图如下:



label的颜色得到了改变,文字信息也加上了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: