簡體   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