首页 文章

动态地改变UITableViewCell的高度

提问于
浏览
-1

我把UITableViewCell放在xib文件中 .
并且,我想根据放在Cell中的UITextView的高度来更改Cell的高度 .

我找到了以下文章 .
http://candycode.io/self-sizing-uitextview-in-a-uitableview-using-auto-layout-like-reminders-app/
我认为这是根据这篇文章 .
但TableViewCell不会根据TextView的高度而改变 .
请告诉我哪里出错了 .

我将详细详细说明我在下面做了什么 .

1.我创建了UITableView和Cell(Xib),如下所示 .

TableView.swift

import UIKit

class TableView: UIView, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {

    @IBOutlet weak var newImage: UIImageView!
    //etc...

    class func instance() -> TableView {
        return UINib(nibName: "TableView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! TableView
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
        return cell
    }

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

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


}

Cell.swift

import UIKit

class NewCellTableViewCell: UITableViewCell {

    let bottomBorder = CALayer()
    let vArchColor   = archColor()

    @IBOutlet weak var textView: UITextView!

    override func awakeFromNib() {
        super.awakeFromNib()
        bottomBorder.frame           = CGRect(x: 20, y: self.frame.size.height - 1.0, width: self.frame.width*2, height: 1.0)
        bottomBorder.backgroundColor = vArchColor.black01.cgColor
        self.layer.addSublayer(bottomBorder)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        print("Selected")
    }

}
  • 我在UITableView中设置了几个必要的值 .

//在TableView.swift中func textViewDidChange(_ textView:UITextView){newTableView.beginUpdates()newTableView.endUpdates()}

//在TableView.swift中func initSomething()

  • 我在Cell(XibFile)中使用了Storyboard并设置了约束 .
    当然,我也取消选中了scrollenabled .

Cell.xib的图片

enter image description here

1 回答

  • 0

    您已经为 heightForRowAtIndexPath: 提供了一个实现,它将在每行的基础上覆盖您在 tableView.rowHeight = ... 中设置的任何常量值 . 从TableViewController中删除此方法,如果文本视图的约束不是固定在所有四边 and 具有高度约束,则应该是黄金的 .

相关问题