iOS CustomTableViewCell : elements not aligining correctly

标签 ios objective-c uitableview

我是在构建应用程序时第一次学习 iOS。在其中一项要求中,UITableViewCell 需要看起来像
enter image description here (PS:这只是一个设计,并没有为此编写代码)

但是,当我设计我的 UITableViewCell 时,它看起来像

enter image description here
enter image description here enter image description here enter image description here

生成这个的代码看起来像

- (void)setTransactionCell:(TransactionCell *)transactionCell transactionModel:(TransactionModel *)transactionModel {
    transactionCell.dateOfMonth.image = [self getDayImage:[UIImage imageNamed:@"1"]];
    transactionCell.dayOfWeek.image = [self getDayImage:[UIImage imageNamed:@"Sun"]];

    transactionCell.name.text = transactionModel.name;
    transactionCell.name.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15];

    transactionCell.amount.text = transactionModel.amount;
    transactionCell.amount.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15];

    transactionCell.categoryImage.image = [self getCategoryImage:[UIImage imageNamed:transactionModel.category]];
    transactionCell.imageView.contentMode = UIViewContentModeCenter;
}

- (UIImage *)getDayImage: (UIImage *) image {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(30, 30), NO, 0);
    [image drawInRect:CGRectMake(0, 0, 15, 15)];
    UIImage *im2 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return im2;
}

- (UIImage *)getCategoryImage:(UIImage *)image {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(40, 40), NO, 0);
    [image drawInRect:CGRectMake(0, 0, 36, 36)];
    UIImage *im2 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return im2;
}

最后,当我运行应用程序时,我看到了
enter image description here

我是新手,不确定哪里出了问题。我拼命尝试将标签和图像拖到每个可能的组合中,但没有任何效果。我遗漏了一些非常基本的东西,你能指导一下哪里出了问题吗?

最佳答案

xibs 上的对象每个对象至少需要 4 个约束。当 label/UIImageView 对象周围有橙色线条时,这意味着约束缺失或冲突,并且通常意味着图像在运行时没有像您预期的那样显示。

对约束进行排序的最简单方法是使用界面构建器,首先我建议选择每个对象并通过从 IB 底部的图标行中选择选项来清除当前约束(见下图)

enter image description here

清除后,要添加新约束,请再次选择该对象并选择您用来清除约束的图标左侧的图标(十字形 - 请参阅选择)

在这张图片中,您会看到一个弹出窗口,让您可以选择添加约束,在本例中,我选择了 UILabel 的顶部和左侧与其最近的顶部和左侧对象的空间约束。您可以通过为该特定约束选择 Spring 来执行此操作,这会变成橙色以表明它已被选中。 (这满足了两个必需的 min 4 约束)。接下来的两个约束(因为我不希望 UIlabel 在那里调整大小)是约束高度和宽度。 (在框中打勾以选择每个)

enter image description here

对于 xib 上的每个 UI 对象都必须重复此操作。一旦它有适当的约束,线条将全部为蓝色,这意味着没有警告(见下图 - UIImageView 的约束以蓝色突出显示)

enter image description here

希望这对您有所帮助,但我建议您阅读更多有关自动布局约束的内容。当您掌握它们时,它们会非常有用,甚至可以制作动画等等。

关于iOS CustomTableViewCell : elements not aligining correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25774732/

相关文章:

ios - Xcode 10 - 多个命令生成 .app

ios - 如何列出iPhone的pdf文件?

ios - 我如何用字典支持一堆类属性?

ios - 从 managedObjectContext 和 tableView 中删除 NSManagedObject

ios - 将 UISearchBar 锁定到 UITableView 的顶部

ios - 什么时候检查用户是否登录?

ios - 不下载数据获取CKAsset URL

ios - 没有越狱的iPhone短信拦截

objective-c - 绘制 super View 时,NSSegmentedControl 的奇怪绘制行为

ios - 如何根据下载的图像大小创建动态大小的行高?