如何正确调整表格视图单元格的大小?

时间:2019-04-29 21:29:35

标签: ios swift uitableview

我的问题是为什么当我放置这些代码时,表格单元格不调整大小,我尝试了两种方式,但仍然无法正常工作。此外,节功能中的节数和行数也不能解决问题。

  tableView.estimatedRowHeight = 100.0
  tableView.rowHeight = UITableView.automaticDimension

    //these 2 functions are supposed to do the same as the two lines of code above 
func tableView(_ tableView: UITableView, heightForRowAtindexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100
}




func numberOfSections(in tableView: UITableView) -> Int {
    return array.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

这是我对表格视图的约束:

tableViewContraints.append(table.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 10))
tableViewContraints.append( table.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 10))
tableViewContraints.append( table.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -10))
tableViewContraints.append( table.bottomAnchor.constraint(equalTo: view.bottomAnchor))
NSLayoutConstraint.activate(textViewContraints) 

这是表cellForRowAt

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    tableView.tableFooterView = UIView()

    let cell = tableView.dequeueReusableCell(withIdentifier: "yeet", for: indexPath)
    cell.textLabel?.text = papel[indexPath.section]
    cell.backgroundColor = .white
    cell.layer.borderColor = UIColor.black.cgColor
    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 8
    cell.clipsToBounds = true
    cell.imageView?.image = UIImage(named: "butterfly")
    cell.sizeToFit()
    cell.layoutIfNeeded()
    let sizp = CGRect(x: 50, y: 50, width: 100, height: 100)
    let textView = UITextView(frame: sizp)
    textView.backgroundColor = .green
    cell.addSubview(textView)

    return cell
}

1 个答案:

答案 0 :(得分:2)

当您为文本视图定义约束时,建议您仅在文本视图及其超级视图之间定义约束。

因此,如果以编程方式添加它,则将其添加到单元格的内容视图中,并定义文本视图和单元格内容视图之间的约束:

class CustomCell: UITableViewCell {
    weak var textView: UITextView!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        configure()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configure()
    }

    func configure() {
        let textView = UITextView()
        textView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(textView)
        textView.isScrollEnabled = false
        self.textView = textView

        NSLayoutConstraint.activate([
            textView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            textView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
            textView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
            textView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10)
        ])
    }
}

请注意禁用滚动,滚动指示了文本视图使用其固有大小来确定其高度。

无论如何,然后我的视图控制器如下:

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    let strings = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                   "Praesent quis nisl justo. Sed ipsum lacus, consectetur quis varius a, ornare sit amet nisl. Curabitur vulputate felis quis pulvinar maximus. Donec sem lorem, ultrices sed ultricies ac, placerat sit amet purus. Nam elementum risus justo, vitae tincidunt mauris sodales vitae. Integer id fermentum quam. Vivamus a arcu neque. In consectetur, velit in sollicitudin finibus, quam nibh rutrum augue, sed dignissim purus ex id elit. Duis sit amet volutpat sapien. Ut leo sapien, iaculis sit amet ultrices eget, fringilla nec dolor.",
                   "Etiam aliquam risus vitae cursus mollis. Fusce vulputate nisi sodales est euismod rutrum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla dignissim ante sed massa viverra, in lobortis ligula semper. Maecenas placerat nec erat ut malesuada."]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 100
    }

}

// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return strings.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.textView.text = strings[indexPath.row]
        return cell
    }
}

结果是:

enter image description here

所有这些,我可能会在情节提要单元原型中添加文本视图及其约束,设置其属性等,然后连接一个出口,然后从根本上简化了我的单元:

class CustomCell: UITableViewCell {
    @IBOutlet weak var textView: UITextView!
}

用更少的代码即可获得完全相同的结果。但是,通过在上面显示我的代码,您可以准确了解我在IB中设置的内容。