0

在我的自定义表格视图单元子类中,文本标签之一的位置取决于 ivar (NSString) 的内容。(即:如果 NSString 为空字符串,则 textlabel 的框架位置不同)。

位置如果更新如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    customOverlayCell *myCell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomOverlayCell"];

    if ([buildingFName isEqual:@""])
    {
        CGRect titleLabelFrame = myCell.titleLabel.frame; 
        titleLabelFrame.origin.y  = 45;
        [myCell.titleLabel setFrame:titleLabelFrame];
    }

    return myCell;
}

我已经删除了部分不相关的代码。

结果是屏幕上出现的第一个单元格的布局被正确更新,但向下滚动后出现的视图的布局没有更新。

我没有正确使用 dequeueReusableCellWithIdentifier 吗?或者还有什么问题吗?

编辑:

EJV 的解决方案:

CGRect titleLabelFrame = myCell.titleLabel.frame; 

if ([buildingFName isEqual:@""])
{
    titleLabelFrame.origin.y  = 45;
} else {
    titleLabelFrame.origin.y  = 37;
}

[myCell.titleLabel setFrame:titleLabelFrame];
4

3 回答 3

1

恐怕,它需要对单元格进行子类化并实现 [UITableViewCell layoutSubviews] 以正确布置单元格的子视图。这就是我对切换表视图单元格执行类似操作的方式:

- (void)layoutSubviews
{
    CGFloat const ESCFieldPadding = 10.0f;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];

    // call super layout
    [super layoutSubviews];

    // obtain widths of elements
    CGFloat contentWidth = self.contentView.frame.size.width;
    CGFloat contentHeight = self.contentView.frame.size.height;
    CGFloat switchWidth = self.switchView.frame.size.width;
    CGFloat switchHeight = self.switchView.frame.size.height;
    CGFloat labelWidth = contentWidth - (4 * ESCFieldPadding) - switchWidth;

    // correctly position both views
    self.textLabel.frame = CGRectMake(ESCFieldPadding, 0.0f, 
                                      labelWidth, contentHeight);
    // it is needed to explicitly resize font as for some strange reason,
    // uikit will upsize the font after relayout
    self.textLabel.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];

    CGRect switchFrame = self.switchView.frame;
    switchFrame.origin = CGPointMake(contentWidth - ESCFieldPadding - switchWidth,
                                     (contentHeight / 2) - (switchHeight / 2));
    self.switchView.frame = CGRectIntegral(switchFrame);

    [UIView commitAnimations];
}
于 2012-07-31T22:03:49.330 回答
1

如果标题标签的框架是动态的,那么当您从表格视图中取出一个单元格时,框架可能处于两种状态中的任何一种(当 buildingFName 为空时以及当它有字符时)。您需要确保在 buildingFName 不为空时设置框架。这样,标题标签的框架将始终正确设置。所以,你需要这样的代码:

CGRect titleLabelFrame = myCell.titleLabel.frame;

if ([buildingFName isEqual:@""])
{ 
    titleLabelFrame.origin.y  = 45;
} else {
    // Change titleLabelFrame
}

[myCell.titleLabel setFrame:titleLabelFrame];
于 2012-07-31T22:08:00.587 回答
0

尝试从您的单元格禁用自动布局

于 2014-03-26T13:57:21.397 回答