When does a UITableView's contentSize get set?

2019-01-08 10:59发布

I have a non scrolling UITableView in a UIScrollView. I set the frame size of the UITableView to its content size.

When I add a row to the UITableView, I call insertRowsAtIndexPaths:withRowAnimation: on the UITableView. Then I call a method to resize the frame of the UITableView:

- (void)resizeTableViewFrameHeight
{
    // Table view does not scroll, so its frame height should be equal to its contentSize height
    CGRect frame = self.tableView.frame;
    frame.size = self.tableView.contentSize;
    self.tableView.frame = frame;
}

It seems though that the contentSize hasn't been updated at this point. If I manually calculate the frame in the above method based on the number of rows and sections, then the method works properly.

My question is, how can I get the UITableView to update its contentSize? I suppose I could call reloadData and that would probably do it, but it seems inefficient to reload the entire table when I'm just inserting one cell.

7条回答
混吃等死
2楼-- · 2019-01-08 11:29
  1. Add observer (in my sample in viewDidLoad

    tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
    
  2. Observe value

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let obj = object as? UITableView {
            if obj == self.tableView && keyPath == "contentSize" {
                if let newSize = change?[NSKeyValueChangeKey.newKey] as? CGSize {
                    //do stuff here
                }
            }
        }
    }
    
  3. Remove observer when not needed

    deinit {
        self.tableView.removeObserver(self, forKeyPath: "contentSize")
    }
    
查看更多
登录 后发表回答