Make text table view(NSTableView) auto resize

To make a iMessage-like chat table view, there is several steps to follow:

  1. Text field should be able to adjust its size automatically.
  2. Image view of bubble should adjust automatically relative to text field.
  3. Table view’s row should be fitted into the row cell’s subview, which include text field and image view.
  4. Let scroller auto scroll to bottum.

Here I use View-based NSTableView to make these:

Table view settings
Table view settings

There is some import constraints to make the three components, NSImageView, NSTextField, NSTableViewCell, keep corresponded size, which is showed below:

Cell contraint settings
Cell contraint settings

You should set NSTextField like below, which will make it auto adjust size to text:

Text field settings
Text field settings

Then use NSTableViewDelegate to adjust height. Read this post: NSTableView automatically adjust height to fit cell view.

Finally, when you add a new row at bottum, you will hope the scroller to scroll to bottum.

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    // tableView is IBOutlet refer to table view.
    self.tableView.insertRowsAtIndexes(NSIndexSet(index: self.tableView.numberOfRows), withAnimation: NSTableViewAnimationOptions.EffectNone)
    self.tableView.noteHeightOfRowsWithIndexesChanged(NSIndexSet(index: self.tableView.numberOfRows - 1))
    // scroll
    self.tableView.scrollRowToVisible(self.tableView.numberOfRows - 1)
})
Junyuan Hong
Junyuan Hong
CSE PhD Student

My research interests include distributed learning, data privacy and deep learning.

comments powered by Disqus

Related