【发布时间】:2013-10-14 14:43:43
【问题描述】:
我认为这里发生了一些奇怪的事情。我有一个带有几个标签作为子视图的原型单元格,并使用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>(
)
这是情节提要本身的片段,显示标签子视图肯定应该在那里。它还显示单元格标识符是正确的。
<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>
(请注意,我将标签设置为愚蠢的数字,以试图使其正常工作)
【问题讨论】:
-
如果您使用
IBOutlets 创建UITableViewCell的子类而不是使用标记,您可能会发现它更容易使用。 -
试试这个 [UITableViewCell 分配问题 - 单元格不是 nil][1] [1]: stackoverflow.com/questions/9865609/…
-
@MichaelKernahan 创建了一个名为
RaceResultCell的单元子类,将标签与IBOutlet链接起来,将cellForRowAtIndexPath中的位更改为引用RaceResultCell,cell.racerNameLabel再次返回为零。 -
@sunkehappy 解析情节提要时不应该在幕后初始化标签吗?
-
即使在执行
cell.racerNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];之后,cell.racerNameLabel仍然为零:s
标签: objective-c ios uitableview