Make text table view(NSTableView) auto resize
To make a iMessage-like chat table view, there is several steps to follow:
- Text field should be able to adjust its size automatically.
- Image view of bubble should adjust automatically relative to text field.
- Table view’s row should be fitted into the row cell’s subview, which include text field and image view.
- Let scroller auto scroll to bottum.
Here I use View-based NSTableView to make these:
There is some import constraints to make the three components, NSImageView, NSTextField, NSTableViewCell, keep corresponded size, which is showed below:
You should set NSTextField like below, which will make it auto adjust size to text:
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)
})