hungry hungry - 3 months ago 24
Swift Question

Resize the textview according to the text content (swift)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellFrame = CGRectMake(0, 0, tableView.frame.width, 100)
var retCell = UITableViewCell(frame: cellFrame)
var textView = UITextView(frame: CGRectMake(8,30,tableView.frame.width-8-8,65))
textView.layer.borderColor = UIColor.blueColor().CGColor
textView.layer.borderWidth = 1
retCell.addSubview(textView)
if(reqGrpIndex == 0){
reqGrpIndex = reqGrpIndex + 1
}
}

func textViewDidChange(textView: UITextView){
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;
}


I saw some post about resizing the textview. However i failed to do that after applying those code. please help. any help will be appreciated.

Answer

Set delegate to uitextview

//If your class is not conforms to the UITextViewDelegate protocol you will not be able to set it as delegate to UITextView
class YourViewController: UIViewController, UITextViewDelegate { 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        textView.delegate = self
    }

    func textViewDidChange(textView: UITextView) { 
        // your resize things
    }
}
Comments