简体   繁体   English

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

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

my question is why does the table cell not resize when I put these codes, I tried both ways and it still does not work.我的问题是为什么当我放置这些代码时表格单元格没有调整大小,我尝试了两种方法但它仍然不起作用。 Also does the number of section and number of rows in section functions got to do anything as being the problem.节函数中的节数和行数也必须做任何事情作为问题。

  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
}

Here are the constraints I have on the tableview:以下是我对 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) 

here is the table cellForRowAt这是表格 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
}

When you define the constraints for your text view, I'd suggest you define them solely between the text view and its superview.当您为文本视图定义约束时,我建议您仅在文本视图及其超级视图之间定义它们。

So, if adding it programmatically, you'd add it to the content view of the cell, and define the constraints between the text view and the cell's content view:因此,如果以编程方式添加它,您需要将它添加到单元格的内容视图中,并定义文本视图和单元格内容视图之间的约束:

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

Note the disabling of the scrolling, which instructs the text view to use its intrinsic size to determine its height.请注意滚动的禁用,它指示文本视图使用其固有大小来确定其高度。

Anyway, then my view controller is as follows:无论如何,那么我的视图控制器如下:

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

That yields:这产生:

在此处输入图片说明

All of that having been said, I'd probably add the text view and its constraints, set its properties, etc., right in the storyboard cell prototype and then hook up an outlet, and then my cell is radically simplified:说了这么多,我可能会在故事板单元原型中添加文本视图及其约束、设置其属性等,然后连接一个插座,然后我的单元就被彻底简化了:

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

That achieves precisely the same result with less code.这可以用更少的代码实现完全相同的结果。 But by showing my code above, you get a sense of precisely what I'd set up in IB.但是通过显示我上面的代码,您可以准确地了解我在 IB 中设置的内容。

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

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