UITableView/UIScrollView如何自动知道ContentSize何时发生变化?

phi*_*uuu 20 uitableview uiscrollview ios

是否有自动方式来了解UITableView/UIScrollView中的ContentSize更改?

phi*_*uuu 28

答案实际上很简单,使用KVO(Key Value Observing);

- (id)initWithFrame:(CGRect)frame tableView:(UITableView *)tableView
{
    // ....
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior context:NULL];
    // ....
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
    if ([keyPath isEqualToString:@"contentSize"]) 
    {
        // Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我还不确定这些旗帜.

  • 还记得`-removeObserver:forKeyPath:context:` (12认同)