Nathan McKaskle Nathan McKaskle - 2 months ago 21
Swift Question

Swift: How do I programmatically add and resize textView to cell?

I'm trying to add a textView to a cell programmatically because I can't use the storyboard for this situation. The below code is my incomplete understanding of how to accomplish this. What I don't know is how to size it to not only match the size (width and height) of the cell, but to resize both the cell and textView to match the amount of text entered.

var textView: UITextView = UITextView(//what goes here??)

cell.addSubview(textView)


I found a similar question for objective C, but not only do I not know objective C, it didn't quite cover the question.

Answer

After playing with it for hours and learning a bunch of stuff from Oliver, I finally figured it out. Turns out it's quite simple to get the textView into the cell, but making both the cell and the textView dynamically grow as you type is apparently another feat entirely. This mostly accomplishes the goal, but I am not satisfied with manually setting the height to 100.

    var cellIdentifier = ""

    if indexPath.section == 1 {
        cellIdentifier = "CellSection1"
        tableView.rowHeight = 100
        cell.frame.size.height = 100
        let cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
        var textView = UITextView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
        cell.addSubview(textView)
        return cell

    } else {

        cellIdentifier = "CellSection0"
        let cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
        cell.textLabel?.font = UIFont.systemFontOfSize(12)
        cell.textLabel?.text = entry.thoughtText
        cell.textLabel?.numberOfLines = 0
        return cell
    }