我定义了一个简单的 CollectionView View ,
当我将委托(delegate)方法放在 ViewController 中时,单元格会正确显示。但是,当我将它移动到 UIView 时,没有调用任何委托(delegate)方法。
有人知道为什么吗?附上代码。
在ViewController中,viewDidLoad
方法,
self.userGrid = [[UserGrid alloc] initWithFrame:self.view.frame];
UserGrid.h
#import <UIKit/UIKit.h>
#import "AvatarViewCell.h"
#import "GridViewLayout.h"
@interface UserGrid : UIView <UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@end
和UserGrid.m
#import "UserGrid.h"
@implementation UserGrid
- (id)initWithFrame:(CGRect)aRect
{
UINib *cellNib = [UINib nibWithNibName:@"AvatarViewCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"avatarCell"];
if ((self = [super initWithFrame:aRect])) {
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView registerClass:[AvatarViewCell class] forCellWithReuseIdentifier:@"avatarCell"];
}
return self;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 12;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"avatarCell";
AvatarViewCell *avatarCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
[avatarCell.avatarImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"website_%ld.jpg", indexPath.row + 1]]];
return avatarCell;
}
@end
** 编辑
我将 init 部分更改为(在 viewDidLoad 中),
self.userGrid = [[[NSBundle mainBundle] loadNibNamed:@"UserGrid" owner:nil options:nil] lastObject];
self.userGrid.frame = self.view.frame;
在viewDidAppear中添加,
- (void)viewDidAppear:(BOOL)animated {
[self.userGrid.collectionView reloadData];
}
添加了 awakeFromNib 方法,但是没有调用委托(delegate)方法......嗯
- (void)awakeFromNib {
UINib *cellNib = [UINib nibWithNibName:@"AvatarViewCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"avatarCell"];
NSLog(@"awake");
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView registerClass:[AvatarViewCell class] forCellWithReuseIdentifier:@"avatarCell"];
}
最佳答案
像这样初始化 UserGrid View
self.userGrid=[[[NSBundle mainBundle] loadNibNamed:@"yourxibName" owner:nil options:nil] lastObject];
self.userGrid.frame=self.view.frame;
你有一个 collectionview 的 IBOutlet 但没有将 View 附加到你的类所以集合不会被初始化
关于ios - 无法将委托(delegate)方法分配给 UIViews?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088877/