不能将委托方法分配给UIViews?

时间:2016-05-07 13:00:57

标签: ios objective-c uiview

我定义了一个简单的CollectionView视图,

当我将委托方法放在ViewController中时,单元格会正确显示。但是,当我将它移动到UIView时,没有调用任何委托方法。

任何人都知道为什么?附上代码。

在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方法,但未调用委托方法... hmm

- (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"];
}

1 个答案:

答案 0 :(得分:1)

像这样初始化UserGrid视图

    self.userGrid=[[[NSBundle mainBundle] loadNibNamed:@"yourxibName" owner:nil options:nil] lastObject];
    self.userGrid.frame=self.view.frame;

您有一个收集视图的IBOutlet,但没有将视图附加到您的班级,因此收集不会被初始化