UICollectionView数据源方法未被调用,但正在init中设置

Jus*_*ral 12 objective-c ios uicollectionview

这是我的源代码

- (id)initWithCollectionView:(UICollectionView *)collectionView
{
self = [super init];

if (self)
{
    self.collectionView = collectionView;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[TWNTweetCell class] forCellWithReuseIdentifier:kCell];
    self.collectionViewLayout = self.collectionView.collectionViewLayout;



    self.tweetArray = @[];
    self.tweetTextArray = @[];

    self.twitter = [STTwitterAPI twitterAPIOSWithFirstAccount];
}

return self;
}

#pragma mark - CollectionView
#pragma mark DataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:      (NSInteger)section
{
return [self.tweetArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
TWNTweetCell *cell = (TWNTweetCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCell forIndexPath:indexPath];

NSDictionary *status = [self.tweetArray objectAtIndex:indexPath.row];

NSString *text = [status valueForKey:@"text"];

cell.usernameLabel.text = screenName;
//    cell.createdAtLabel.text = dateString;

cell.autoresizingMask = UIViewAutoresizingFlexibleWidth;

UITextView *textView = [self.tweetTextArray objectAtIndex:indexPath.row];
[cell setTweet:text withTweetTextView:textView];

return cell;
}
Run Code Online (Sandbox Code Playgroud)

所有方法都不会被断点完全中断.这些推文被加载到日志中,所以我知道其他一切都没问题,它只是没有识别集合视图.是的,我已经设定了

任何人都知道最新情况怎么样?

Jul*_*ról 42

这不是你的情况,对于那些来这里没有被调用的数据源方法有问题的人来说可能会有所帮助.它可以分配数据源,如:

collectionView.dataSource = MyDataSource()
Run Code Online (Sandbox Code Playgroud)

这是错误的,因为dataSource是一个弱引用,因此需要在创建它之后通过一些强引用来存储它.在ViewController中添加了一个私有属性以保留强引用,初始化然后分配它可以解决问题.


Mic*_*ann 3

有几件事:

1)在(且仅在)你的“ init”方法中,使用你的@property的底层实例变量。那是,

_collectionView = collectionView;
_collectionView.dataSource = self;
_collectionView.delegate = self;
Run Code Online (Sandbox Code Playgroud)

这称为“直接访问”,更多信息可以在这个相关问题中看到。

2) 在您的 .h 文件中,确保声明您的对象符合数据源和委托协议。例如

@interface JustinViewController : UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>
Run Code Online (Sandbox Code Playgroud)