iphone - 绘制具有可变高度的 UITableViewCell 时宽度不正确

标签 iphone ios uitableview

地址单元格需要可变高度。

viewWillAppear 中,我绘制了一个测试单元格以捕获 ivar 中的标签高度。

在委托(delegate)方法 tableView:heightForRowAtIndexPath 中,我使用 ivar 设置实际地址单元格的高度。

代码:

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

UITableViewCell *testCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"addressCell"] autorelease];

testCell.textLabel.text = @"Address";
testCell.detailTextLabel.text = [selectedPatient valueForKey:@"address"];
testCell.selectionStyle = UITableViewCellSelectionStyleNone;
testCell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
testCell.frame = CGRectMake(0,0,100,30);
[testCell addSubview:testCell.detailTextLabel];
[testCell sizeToFit];

CGSize maxSize;

// HERE is where the problem occurs
// maxSize.width is 35 when it should be 200
maxSize.width = testCell.detailTextLabel.frame.size.width;
//

maxSize.height = 500;

UIFont *font = testCell.detailTextLabel.font;

CGSize testSize = [[selectedPatient valueForKey:@"address"] sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];

addressLabelHeight = testSize.height;

[testCell removeFromSuperview];
}

获取测试单元格的宽度是个问题。当 NSLog'ing cellForRowAtIndexPath: 它显示宽度为 200,但我的 testCell 的宽度只有 35。这导致高度太大,显示一个单元格有太多空白。

我通过设置 maxSize.width = 200 解决了这个问题,但我很好奇动态获取 detailLabel 的宽度我做错了什么?

最佳答案

maxSize.width 将是文本的宽度。您从 @"address" 收到的文本是什么?我敢打赌宽度大约为 35 点。

顺便说一句,你为什么要这样做:

// This is legal, but a strange size
testCell.frame = CGRectMake(0,0,100,30);

// This is redundant I believe 
[testCell addSubview:testCell.detailTextLabel];

// Does this help you at all?
[testCell sizeToFit];

tableView:willDisplayCell:atIndexPath: 之前,您不能真正相信单元格的宽度。这就是您要进行任何最终布局的地方。出于您的目的,您可能应该选择您希望地址的宽度(如果您愿意,可以设置 200 磅),然后强制将其设置为该宽度,而不是询问它有多大。

关于iphone - 绘制具有可变高度的 UITableViewCell 时宽度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7070979/

相关文章:

ios - 将数据添加到 Singleton 实例数组

ios - GPUImageMovie : how to show the first frame of the video after playback is completed?

ios - 在表格单元格上播放视频

iphone - uitableview 中的 resignFirstResponder 崩溃

ios - 类 AppDelegate : UIResponder, UIApplicationDelegate 线程 1:信号 SIGABRT

iphone - UIApplicationDelegate协议(protocol)中神秘的+initialize方法: Why can't I see it in the documentation?

iphone - 比较两个 NSString 类型的字符串时应用程序崩溃

iphone - 提交应用到苹果应用商店后如何更改 "Version Release Control"

ios - 在 Xcode 4.4 中使用不受支持的编译器

ios - UITableViewCell 标签显示不正确