【发布时间】:2015-08-29 22:46:31
【问题描述】:
我遇到了一个让我发疯一段时间的问题,我无法解释出了什么问题。我有一个 UITableView 有不同的视图和 3 个原型单元可供选择。如果我在我的小组模式中,我会从我的故事板中展示原型 applicationCell。第一个条目总是看起来不错,但如果我有 2 个图像,则第二个条目中的图像会加倍并调整图像大小,以便显示两次 - 尺寸正确并再次调整为单元格高度(每个单元格中也只有一个图像),请参阅图像:
这里是导致问题的相关代码:
- (UITableViewCell *)tableView:(UITableView *)table
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(app == nil && groupedMode) {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"applicationCell"
forIndexPath:indexPath];
UILabel *head = (UILabel*)[cell viewWithTag:2];
UILabel *badge = (UILabel*)[cell viewWithTag:3];
UILabel *lastMsg = (UILabel*)[cell viewWithTag:4];
UIImageView *imgView = (UIImageView*)[cell viewWithTag:1];
ApplicationEntity *a = [applications objectAtIndex:indexPath.row];
head.text = a.name;
badge.text = [NSString stringWithFormat:@"%lu",(unsigned long)a.messages.count];
ImagesEntity *ie = [ImagesEntity imageByAppId:a.appToken imgId:0];
NSLog(@"V %li",(long)indexPath.row);
//imgView.contentMode = UIViewContentModeScaleAspectFit;
imgView.image = ie.computedImage;
CGRect r = imgView.bounds;
NSLog(@"bounds %f %f %f %f",r.origin.x,r.origin.y,r.size.width,r.size.height);
r = imgView.frame;
NSLog(@"frame %f %f %f %f",r.origin.x,r.origin.y,r.size.width,r.size.height);
imgView.bounds = CGRectMake(0,0,48,48);
imgView.frame = CGRectMake(11,2,48,48);
cell.tag = indexPath.row;
if(cell.gestureRecognizers.count == 0) {
UITapGestureRecognizer * gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(applicationClicked:)];
[cell addGestureRecognizer:gr];
}
lastMsg.text = [dateFormatter stringFromDate:a.lastMessage];
r = imgView.bounds;
NSLog(@"after bounds %f %f %f %f",r.origin.x,r.origin.y,r.size.width,r.size.height);
r = imgView.frame;
NSLog(@"after frame %f %f %f %f",r.origin.x,r.origin.y,r.size.width,r.size.height);
return cell;
}
UIImageView 有一个 width = height = 48 的约束。到目前为止我测试和发现的内容:
- 将图像设置为零显示无图像 = 无错误
- 不分配新图像不会显示错误。
- 只分配一次新图像有效。
-
当它发生时,UIImageView 会获得新的边界和框架,但将它们直接设置回正确的值并不能帮助查看日志
V 0 界限 0.000000 0.000000 48.000000 48.000000 帧 11.000000 2.000000 48.000000 48.000000 界限后 0.000000 0.000000 48.000000 48.000000 帧后 11.000000 2.000000 48.000000 48.000000 V 1 界限 0.000000 0.000000 320.000000 110.000000 帧 0.000000 110.000000 320.000000 110.000000 界限后 0.000000 0.000000 48.000000 48.000000 帧后 11.000000 2.000000 48.000000 48.000000
110 高度是单元格高度,320 是宽度。它违反了约束。此外,我分配的图像是 96x96 像素,因此在 HDPI 显示器中显示效果很好。
顺序和图像可能会改变,所以我需要分配正确的图像。
任何想法为什么会发生这种情况以及如何防止这种情况发生?
【问题讨论】:
-
(只是一个建议)为 UILabel 和 UIImageView 创建变量也是很好的编码实践 imo。它将使您的代码更具可读性,并且您不会遇到此类问题。并且使用自定义单元格也使工作更加独立和干净。
标签: ios objective-c xcode uitableview uiimageview