我使用使用自定义的UITableViewCell子类,NoteCell
表视图。子类有两个文本标签,一个名称标签和一个日期标签,它们并排放置在单元格中。我的目标是让名称标签自行调整,以便无论如何显示完整日期。如何动态调整UITableViewCell中两个文本标签宽度的大小?
中的cellForRowAtIndexPath,我试图计算和设定的两个文本视图的宽度,这样的日期得到充分的展示和名字标签被截断。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NoteCell";
NoteCell *cell = (NoteCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.dateLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
cell.nameLabel.text = @"A name that should be truncated";
cell.dateLabel.text = @"A long date to use as an example";
// Set the widths
// First calculate how wide the date label needs to be.
cell.dateLabel.text = @"A really long date";
CGSize dateLabelSize = [cell.dateLabel.text sizeWithFont:cell.dateLabel.font];
CGFloat dateExpansionAmount = fabsf(dateLabelSize.width - cell.dateLabel.frame.size.width) + 10.0f;
cell.dateLabel.frame = CGRectMake(cell.dateLabel.frame.origin.x - dateExpansionAmount,
cell.dateLabel.frame.origin.y,
dateLabelSize.width,
cell.dateLabel.frame.size.height);
CGFloat nameLabelWidth = cell.dateLabel.frame.origin.x - cell.nameLabel.frame.origin.x;
cell.nameLabel.frame = CGRectMake(cell.nameLabel.frame.origin.x,
cell.nameLabel.frame.origin.y,
nameLabelWidth,
cell.nameLabel.frame.size.height);
}
不幸的是,因为我不认为我设置/正确计算帧边界做的结果是不正确的。看到下面的图片。
忽视的问题与框架计算是否有更好的方式来处理这个问题,或者是手动定位文本标签框架的唯一途径?
您是否已尝试在被问到的标签上设置autoResize属性? – 2012-02-24 23:33:55
你的意思是说,设置autoresize属性,即支柱和弹簧? - 如果是这样,那么当设备旋转时,将调整标签的大小以扩大或缩小。 – 2012-02-24 23:40:33
您正确设置了日期标签的调整大小掩码,但未设置名称标签。它应该具有灵活的宽度和固定的右边距。 – sosborn 2012-02-25 00:37:31