【问题标题】:UITableView/UIScrollView how to automatically know when ContentSize changes?UITableView/UIScrollView 如何自动知道 ContentSize 何时发生变化?
【发布时间】:2012-07-02 21:17:02
【问题描述】:

是否有一种自动方式来了解 UITableView/UIScrollView 中的 ContentSize 变化?

【问题讨论】:

  • 什么需要注意内容大小的变化? “UITableView”和“UIScrollView”对象本身,或者包含它们的东西,还是其他东西?

标签: ios uitableview uiscrollview


【解决方案1】:

答案其实很简单,使用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
    }
}

不过我还不确定这些标志。

【讨论】:

  • 也记得-removeObserver:forKeyPath:context:
  • 我通常把-removeObserver:forKeyPath:context:放在-dealloc方法中。
【解决方案2】:

对于那些不喜欢 KVO 的人:

- (void)setContentSize:(CGSize)contentSize {
    [super setContentSize:contentSize];
    // Do something.
}

是的,只需使用super 访问父方法。这假设你继承 UIScrollview/TableView/CollectionView

【讨论】:

  • 更好的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多