繁体   English   中英

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

[英]how to properly resize the table view cell?

我的问题是为什么当我放置这些代码时表格单元格没有调整大小,我尝试了两种方法但它仍然不起作用。 节函数中的节数和行数也必须做任何事情作为问题。

  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
}

以下是我对 tableview 的约束:

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
}

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

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

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
    }
}

这产生:

在此处输入图片说明

说了这么多,我可能会在故事板单元原型中添加文本视图及其约束、设置其属性等,然后连接一个插座,然后我的单元就被彻底简化了:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM