ios - 为什么元素会无缘无故停止显示?

标签 ios uitableview

您好,我是一名 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]; // ???

您不应将内置的 textLabeldetailTextLabel 与您自己的其他 subview 混合使用。

所以基本上要点是:如果你想自定义单元格的内容,而不是仅仅使用内置的 textLabeldetailTextLabel,那么你需要停下来回去学习如何做。

哦,还有一件事。你说:

I keep notice things inexplicably disappearing or going wrong in display of build

没有。停止。事情不会莫名其妙地发生。如果你怀疑有神秘力量潜入并把事情搞砸,比如宇宙射线,你就学不会编程。如果你的代码坏了,就坏了它。学会面对这样一个事实:如果您的代码没有按照您的预期运行,就做错了什么。除非你接受这种思维方式,否则你永远不会成为一名优秀的程序员。

关于ios - 为什么元素会无缘无故停止显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889089/

相关文章:

Swift 2.0/Parse - 查询完成速度不够快,因此应用程序在启动时崩溃

ios - 具有重复和延迟的 animateKeyframes 无法按预期工作

ios - 在 iOS 中以编程方式创建 UINavigationController

ios - Objective C 中方法名称的命名约定

ios - Swift 4 - 如何从 UICollectionViewCell 中嵌套的按钮以编程方式激活 segue

ios - 为什么我在 Xamarin iOS 中收到 "Must translate autoresizing mask into constraints to have _setHostsLayoutEngine:YES"错误?

ios - 如何将数据保存到模型coredata

ios - 在边界外接收触摸事件

ios - 带有图像的 UITableViewCell 动态高度

ios - 更改 UITableViewCell 中元素的动态高度约束