简体   繁体   中英

Subviews of UITableViewCell seem to randomly disappear after dequeueReusableCellWithIdentifier

In my iOS 7.0 App:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...

// AttemptCell is a prototype cell, currently using the "Right Detail" preset 
// style and the little information accessory.
static NSString *CellIdentifier = @"AttemptCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

assert(cell != Nil);

if (cell.contentView.subviews.count == 2)
{
    UILabel *attemptLabel = (UILabel*)cell.contentView.subviews[0];
    attemptLabel.text = attempt.attempt;

    UILabel *analysisLabel = (UILabel*)cell.contentView.subviews[1];
    analysisLabel.text = [attempt analysis];

    cell.tag = indexPath.row;
}
else
{
    // Something has gone very wrong.
    UILabel *attemptLabel = (UILabel*)cell.contentView.subviews[0];
    attemptLabel.text = @"Error";
}

The question is why does the (UILabel*)cell.contentView.subviews[1] sometimes disappear causing the error block to be entered.

This table view shows one custom keyboard entry cell (UITextField) which always appears last. The keyboard entry cell is also prototyped, but with a different dequeue cell identifier. The problem is randomly seen when the keyboard pops up and is closed. Keyboard popping up causes some AttemptCells to go out of view and closing the keyboard causes the AttemptCells to come back into view.

What you are doing is wrong. Don't rely on the view hierarchy of a private class, certainly don't depend on the number of views in a hierarchy and really don't depend on a view being in a certain position of the sub views array. Your error block may not be entered because a sub view has "disappeared" - an extra view could have been added, all you're checking for is that the count of the sub views is equal to 2.

If you're using one of the standard cell layouts, use the textLabel and detailTextLabel properties. If you're using a subclass, use outlets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM