UICollectionView数据源方法没有被调用,而是在init中设置
这是我的源代码
- (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; }
所有的方法都不会因断点而中断。 微博正在被加载到日志中,所以我知道一切都好,它只是不认识收集视图。 是的,我已经设置了
任何人有什么想法是怎么回事?
这不是你的情况,它可能会有助于其他人来到这里有问题的数据源方法不被称为。 这可能是分配数据源,如:
collectionView.dataSource = MyDataSource()
这是错误的,因为dataSource是一个弱引用,所以需要通过一些强大的引用来存储它,以创build它后生存。 在ViewController中添加一个私有属性,以保持强引用,初始化,然后分配它修复问题。
几件事情:
1)在(并且只在)你的“ init
”方法中,使用你的@property的底层实例variables。 那是,
_collectionView = collectionView; _collectionView.dataSource = self; _collectionView.delegate = self;
这就是所谓的“直接访问”, 在这个相关的问题上可以看到更多的信息 。
2)在.h文件中,确保声明你的对象符合数据源和委托协议。 例如
@interface JustinViewController : UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>
几点build议:
- 在
viewDidLoad
执行所有的UICollectionView
设置和configuration。 - 确保从其他类调用create
init
方法 - 你的
tweetArray
也是空的,所以如果调用项目数的方法,它将不会返回任何其他方法将不会被调用
将collectionView添加到视图层次结构。
在init方法中,您设置属性(self.collectionView),但不要将collectionView添加到视图层次结构中。 所以collectionView将不会调用任何数据源或委托方法。
在init
方法的末尾调用[collectionView reloadData]
。 收集视图需要被告知填充自己。 我假设UICollectionViewController
在内部执行此操作,但是您似乎没有使用UICollectionViewController
(或者至less不是以通常的方式)。
我在storyboard和linked datasource和delegate中创build了集合视图,但是它们并没有在Swift 3.0的Xcode 8.0中被调用。 尝试了多种事情,但解决scheme是在类声明行中声明委托和数据源:
类ViewController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {…}
以前,当我们通过故事板链接委托和数据源时,它不是必需的,可能是一个错误:)