【问题标题】:Swift - UITableViewCell height according to UITextView layout constraintSwift - 根据 UITextView 布局约束的 UITableViewCell 高度
【发布时间】:2016-11-02 08:08:59
【问题描述】:

在我的表格视图单元格中有 3 个对象;一个图像视图、标签和一个文本视图。

这就是我设置 textView 及其约束的方式:

textView.translatesAutoresizingMaskIntoConstraints = false
textView.textColor = UIColor.blue
textView.font = UIFont.systemFont(ofSize:15.0)
textView.textAlignment = NSTextAlignment.left
textView.isScrollEnabled = false

**注意 self 是一个包含 textView 的 UIView。表格视图单元格的内容视图将包含此 UIView

self.addConstraints([
            textView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 10.0),
            textView.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10.0),
            textView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10.0),
            textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 20.0)
            ])

我做了isScrollEnabled = false,这样textView的高度就根据它的内容来计算了

对于我的 UITableView,我这样做了:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

使用上面的代码,我的 tableviewcell 没有显示正确的高度。我相信这是因为我的 textview 高度约束给 tableviewcell 内容视图一个错误的高度。

我该如何解决这个问题?

【问题讨论】:

  • 设置isScrollEnabled = false不会影响计算textView的高度
  • @alexburtnik 和 heightAnchor 确实会根据其高度更改 textView。对不起,如果我的解释不清楚
  • @alexburtnik 我能够根据内容更改 textView 的高度,但仍然无法更改表格视图单元格的高度

标签: ios swift


【解决方案1】:
  1. 设置isScrollEnabled = false不会影响计算textView的高度。
  2. 为了根据 textView 的内容调整单元格大小,除了 top(=) 之外,您还应该将 bottom(=) 约束添加到您的 textView 可选高度(>=)

【讨论】:

    【解决方案2】:

    您是否尝试过使用tableView(heightForRowAt:) 委托方法?

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return textView.frame.height // Assuming you have a reference to the textview
    }
    

    【讨论】:

    • @imstillalive 哈哈,这是不必要的,完全错误的评论。
    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2022-01-21
    • 2020-12-25
    • 2014-10-21
    相关资源
    最近更新 更多