UITextView and cell dynamically update height based on content of textview?

后端 未结 1 995
深忆病人
深忆病人 2020-12-18 15:06

I have been having an issue regarding a UITextView inside a custom cell. The textView works perfectly besides my issue. I have the UITextViewDelegate methods setup so when

相关标签:
1条回答
  • 2020-12-18 15:52

    This works for ios 7 too

    this goes into your tableviewcell

    protocol HeightForTextView {
        func heightOfTextView(height: CGFloat)
    
    }
    
    class TableViewCell: UITableViewCell {
    
        @IBOutlet weak var textView: UITextView!
    
        var delgate:HeightForTextView?
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
    
        func textViewDidChange(textView: UITextView) {
    
            var fixedWidth: CGFloat = textView.frame.size.width
            var newSize: CGSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max))
    
            if let iuDelegate = self.delgate {
    
                iuDelegate.heightOfTextView(newSize.height)
            }
    
    
        }
    
    }
    

    your tableview controller should be

     class TableViewController: UITableViewController,HeightForTextView {
    
            var textViewHeight = CGFloat()
    
        //In your cell for row method set your your delegate 
     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
        cell.delgate = self
    
        return cell
    }
    
    
    //delegate method
    
        func heightOfTextView(height: CGFloat) {
    
        textViewHeight = height
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
    
        }
    
     override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
                return textViewHeight + 70
        }
    
        }
    
    0 讨论(0)
提交回复
热议问题