您好,我是一名 IOS 新手,正在尝试使用详细信息应用程序处理表格 View 。我正在使用全新的 macbook air 和 Xcode 6。但是,我一直注意到在构建显示中莫名其妙地消失或出错。我尝试清洁无济于事。
我没有更改下面显示 subview 和右侧图像的表格的代码,但现在只显示头部,不再是副标题或任何图片, subview 中的标准图像和我添加的右侧图像.程序是否存在错误,或者在我没有注意到的情况下有什么东西潜入了我的代码?
我唯一做的就是在一个单独的细节 Controller 中,添加一个图像导出属性和另一个属性,这两个属性都不会引发警告,但为什么这会弄乱 tableviewcontroller 场景?
这是工作表的代码,但现在不显示子文本或图像,尽管它显示了标题:
static NSString *protoCell = @"Cell";
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:protoCell forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = @"head";
cell.detailTextLabel.text = @"sub";
cell.imageView.image = [UIImage imageNamed:@"pic.png"];
UIImageView *rightimage;
rightimage = [[UIImageView alloc] initWithFrame:CGRectMake(225.0,0.0,80.0,45.0)];
rightimage.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:rightimage];
rightimage.image = [UIImage imageNamed:@"pic.png"];
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.layer.masksToBounds=YES;
cell.imageView.layer.cornerRadius=20.0;
cell.imageView.frame = CGRectMake(20, 20, 500, 50);
return cell;
}
最佳答案
您的代码有很多问题。最主要的是您忘记了单元重用。你说
[cell.contentView addSubview:rightimage];
对于 cellForRowAtIndexPath:
的每次 调用。但是对于 同一个 单元格,它被调用了很多次,因为单元格被重用了。因此,如果您的表中有 100 行,您最终可能会在同一个单元格中得到 100(或 1000,或 10000)份 rightImage
的副本。
另外,你是这样说的:
cell.textLabel.text = @"head";
cell.detailTextLabel.text = @"sub";
[cell.contentView addSubview:rightimage]; // ???
您不应将内置的 textLabel
和 detailTextLabel
与您自己的其他 subview 混合使用。
所以基本上要点是:如果你想自定义单元格的内容,而不是仅仅使用内置的 textLabel
和 detailTextLabel
,那么你需要停下来回去学习如何做。
哦,还有一件事。你说:
I keep notice things inexplicably disappearing or going wrong in display of build
没有。停止。事情不会莫名其妙地发生。如果你怀疑有神秘力量潜入并把事情搞砸,比如宇宙射线,你就学不会编程。如果你的代码坏了,你就坏了它。学会面对这样一个事实:如果您的代码没有按照您的预期运行,您就做错了什么。除非你接受这种思维方式,否则你永远不会成为一名优秀的程序员。
关于ios - 为什么元素会无缘无故停止显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889089/