简体   繁体   中英

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:

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

      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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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