我正在尝试将 UITableView 与 .xib 文件一起使用。我过去用 Storyboard做过,你在动态原型(prototype)中声明一个重用 ID。我在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
函数中有这段代码应该可以工作:
NSString *ReuseId = @"DefaultCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseId];
if (cell == nil) {
NSLog(@"cell == nil");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ReuseId];
}
但是,当我运行它时,不是打印 cell == nil
而是为每一行打印一次。
为什么??
谢谢。
最佳答案
你有多少行?它应该首先在 iPhone 上创建最多 11 或 12 个。取决于表格 View 的高度和单元格的高度。
因此,如果行数少于 View 中容纳的单元格,则单元格重用将永远不会发生,也不需要。
if (cell == nil) {
NSLog(@"cell == nil");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ReuseId];
} else {
NSLog(@"We have a reused cell!");
}
尝试多次重复您的行并缓慢滚动。现在,每次您要在 View 上滚动新单元格的第一个像素时,它都应该打印“我们有一个重用的单元格!”。
关于ios - dequeueReusableCellWithIdentifier : returns nil even after creating cell instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574270/