locked
how to make UITextView height dynamic according to text length ? RRS feed

  • Question

  • User306227 posted

    how to make UITextView height dynamic according to text length? in tableview

    Friday, June 12, 2020 3:57 AM

Answers

  • User369979 posted

    Firstly, add leading, top, trailing, and bottom constraints to your UITextView. And then add a height constraint so that it won't be too small when there's no text in it. Here are my constraints: I set its height to greater than 44. Therefore, it won't restrict the height growing. Secondly, disable the scrollable of the UITextView. Finally, we need to notify the UITableView to change the cell height when UITextView changes. Define an event in your custom view cell and trigger it when text changed:

    public partial class MyTableViewCell : UITableViewCell
    {
        public event Action Update;
        public MyTableViewCell (IntPtr handle) : base (handle)
        {
        }
    
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();
    
            MyTextView.Delegate = new MyTextViewDelegate(this);
        }
    
        public void UpdateCell()
        {
            Update();
        }
    }
    

    Register this event in the controller:

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        MyTableViewCell cell = tableView.DequeueReusableCell("Cell") as MyTableViewCell;
        cell.Update += () =>
        {
            tableView.BeginUpdates();
            tableView.EndUpdates();
        };
    
        return cell;
    }
    

    Here is the effect: Attached my sample here for your reference.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, June 12, 2020 8:03 AM