我认为这里发生了一些奇怪的事情。我有一个原型单元格,其中包含几个标签作为子视图,并使用viewWithTag
来查找它们以设置其文本。在同一项目中,我已经做过3次了,所以我不知道可能出了什么问题。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Result Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *racerNameLabel = (UILabel*) [cell viewWithTag:5002153];
//more labels ...
return cell;
}
如果我设置了断点,racerNameLabel将会是nil且单元格没有子视图:
(lldb) po [[cell contentView] subviews]
(id) $5 = 0x08161da0 <__NSArrayI 0x8161da0>(
)
这里是Storyboard的片段,显示标签子视图肯定存在。它还显示单元格标识符是正确的。
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="Result Cell" rowHeight="80" id="hGh-MB-iBH">
<rect key="frame" x="0.0" y="22" width="382" height="80"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="382" height="79"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" tag="5002153" contentMode="left" text="Racer Name" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Sf6-ol-OLA">
<constraints>
<constraint firstAttribute="width" constant="166" id="iI1-0U-gN8"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<color key="highlightedColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</label>
(请注意,我将标签设置为一个愚蠢的数字,是因为在努力让它工作时感到沮丧)
(请注意,我设置标签为一个愚蠢的数字,是为了在尝试使其工作时感到失望)
UITableViewCell
的子类,并使用IBOutlet
,而不是使用标签,那么您可能会发现它更容易使用。 - Michael KernahanRaceResultCell
的单元格子类,使用IBOutlet
将标签连接起来,在cellForRowAtIndexPath
中更改了位以引用RaceResultCell
,但是cell.racerNameLabel
的结果又变成了nil。 - Dan2552