首页 文章

如何根据UITextView子视图的大小调整UITableViewCell的大小?

提问于
浏览
0

目前,我可以根据其中的文本量成功调整我的UITextView的大小 .

我的问题是这个UITextView在UITableViewCell中 . 我试图做的是使用调整大小的UITextView的高度来调整单元格的大小,方法是访问它的框架并设置它的高度 .

这是我的代码:

//dynamically resize textview and cell based on content
                self.aboutMeTextView.text = profile["aboutMe"] as String
                self.aboutMeTextView.sizeToFit()
                self.aboutMeTextView.layoutIfNeeded()
                var frame = self.aboutMeTextView.frame as CGRect
                frame.size.height = self.aboutMeTextView.contentSize.height
                self.aboutMeTextView.frame = frame

                var cellFrame = self.aboutMeCell.frame as CGRect
                cellFrame.size.height = self.aboutMeTextView.contentSize.height * 2

                self.aboutMeCell.frame = cellFrame

它只是无法正常工作 . textView调整大小,但单元格没有正确调整大小,我的scrollView甚至不会向下滚动,以便我看到整个调整大小的textview . 我猜我是否能成功设置单元格高度,scrollView高度会自动调整 .

我看过类似的问题,但他们没有帮助我 .

会感激一些帮助 .

谢谢你的时间

2 回答

  • 0

    你可以使用 UITableView -method heightForRowAtIndexPath

    API Documentation

    它返回一行的高度 . 因此,您可以使用当前单元格中的标签,并将单元格的高度设置为标签的高度:

    override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
        var cellID = "Cell"
        var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID)  as UITableViewCell
    
        var yourLabelHeight = cell.yourLabel.size.height
        return yourLabelHeight
    }
    
  • 0

    您可以像这样调用UITableView.beginUpdates()和UITableView.endUpdates():

    extension TableViewCell: UITextViewDelegate {
    
            var delegate: TableViewController!
            var row: Int!
    
            func textViewDidChange(_ textView: UITextView) {
    
                delegate.tableView.beginUpdates()
                delegate.tableView.endUpdates()
    
            }
    
        }
    
    
        class TableViewController: UITableViewController {
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
                tableView.rowHeight = 44
                tableView.rowHeight = UITableViewAutomaticDimension
                tableView.estimatedRowHeight = 44
    
            }
    
            override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
    
                cell.delegate = self
                cell.row = indexPath.row
    
                return cell
    
            }
    
        }
    

    确保在表格视图单元格中为文本视图设置了约束 .

相关问题