我在这一基本问题上奋斗了一天多,这让我发疯了!有趣的是,我在其他屏幕上也有类似的东西,而且效果很好!我已经做了1000次,但从未经历过如此奇怪的事情。也许仅在iOS 8中这种行为?
在我非常简单的原型单元上,我有两个带有标签102和103的标签。但是当我想给它们设置文本时,它们始终为nil。
我仔细检查了标识符的正确性,并且该标签与情节提要中的标签相同。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * identifier = @"secondReusableIdentifier";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
for (UIView *subview in [cell subviews]) {
NSLog(@"subview: %lu", subview.tag); // prints 0
}
UILabel * label1 = (UILabel *)[cell viewWithTag:102]; // returns nil
UILabel * label2 = (UILabel *)[cell viewWithTag:103]; // returns nil
if (self.items.count) {
MyObject *obj = [self.items objectAtIndex:indexPath.row];
label1.text = obj.someProperty;
fuelPrice2.text = obj.someOtherProperty;
}
}
return cell;
任何建议,将不胜感激。
在您的代码中,您正在创建一个新的单元,该单元与情节提要中的单元不同。
更改此方法:这是旧方法,或者当单元格通过代码或笔尖使用而您不使用情节提要时使用的方法。此代码表示。
NSString * identifier = @"secondReusableIdentifier";
// If I have available a cell with this identifier: secondReusableIdentifier, let's go to use it.
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil){
// If not, we create a new cell with this identifier. This methods is previous to storyboard, and this methods create a new cell, but does´t look in Storyboard if this identifier exist, or something like that.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
为此,从另一方面来说,当苹果公司启动情节提要时,框架便以这种方式增长:如果有一个免费的单元格,请使用它,否则,它将在情节提要中查找具有此标识符的单元格,并使用此信息。(您也可以通过代码和nib文件使用此方法,但是必须在之前注册该类。)。
// Be sure than: "secondReusableIdentifier", it's its identifier in storyboard
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondReusableIdentifier" forIndexPath:indexPath];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句