【问题标题】:Issue with auto layout - vertical spacing自动布局问题 - 垂直间距
【发布时间】:2018-01-01 13:22:02
【问题描述】:

在带有 Swift 3 的 Xcode 8 中,我使用了带有自动布局的自定义单元格。从 JSON 插入到单元格中的信息,所以我的代码如下所示:

    //the method returning each cell of the list
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = self.tableView.dequeueReusableCell(withIdentifier: "Feedcell", for: indexPath) as! FruitTableViewCell

    //getting the hero for the specified position
    let hero: List_Feed
    hero = heroes[indexPath.row]

    cell.labelAnswer.text = hero.answer
    cell.labelQuestion.lineBreakMode = .byWordWrapping
    cell.labelQuestion.text = hero.question
    cell.labelQuestion.sizeToFit()
    cell.labelAnswer.sizeToFit()

    return cell
    }

问题是每个单元格的 labelQuestion 高度相同,但文本大小和行大小不同。如何解决这个问题? :c

【问题讨论】:

  • 您的标签高度因 cell 的高度而增加。尝试给背景颜色以找出增加了哪个标签高度
  • 如果你今天的标签是一个内衬标签然后给它高度限制
  • @PrashantTukadiya 抱歉,没用,我附上了一张照片来提问
  • 请查看答案
  • @PrashantTukadiya 我已经评论过了

标签: ios swift autolayout interface-builder


【解决方案1】:

由于单元格正在重用标签,因此您必须在使用下一个单元格之前清空标签

public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = self.tableView.dequeueReusableCell(withIdentifier: "Feedcell", for: indexPath) as! FruitTableViewCell

    //EMPTY LABELS
    cell.labelAnswer.text = ""
    cell.labelQuestion.text = ""

     self.layoutIfNeeded()

    //getting the hero for the specified position
    let hero: List_Feed
    hero = heroes[indexPath.row]

    cell.labelAnswer.text = hero.answer
    cell.labelQuestion.lineBreakMode = .byWordWrapping
    cell.labelQuestion.text = hero.question
    cell.labelQuestion.sizeToFit()
    cell.labelAnswer.sizeToFit()

    return cell
}

希望对你有帮助

【讨论】:

  • 非常感谢,亲爱的朋友,但还是不行:/
  • 我发现问题出在哪里。由于文本是西里尔文,一个字母占用 3-4 个字母的空间,因为它是一个代码,实际上不是字母。以及如何解决这个问题?
【解决方案2】:

1- 将今天标签的垂直内容拥抱优先级设置为 1000

2- 将标签底部 [即今天标签下] 钩到 imageView 的顶部下方

3- 将最下标签的底部钩到 contentView 的底部

编辑:

cellForRowAt

中的返回单元格之前添加这 2 行
  cell.layoutSubviews()

  cell.layoutIfNeeded()

【讨论】:

  • 谢谢你的回答,朋友。我做过 1-,但我不明白 2- 是什么。并且 3- 已经被钩到了底部。请检查问题以添加照片。
  • 如果最底部的标签是一行,则 2 和 3 将与您所做的一样
  • 不,问题是问题标签垂直拉伸,我不知道为什么
  • 是的,红色的
  • 也用它做第 1 步