2012-07-02 12 views

Trả lời

25

Câu trả lời thực sự đơn giản khi sử dụng KVO (Quan sát giá trị khóa);

- (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 
    } 
} 

Tôi chưa chắc chắn về cờ.

+0

Tôi biết điều này đã được một thời gian trước nhưng cảm ơn bạn rất nhiều! – ryanwils

+11

Cũng nhớ đến '-removeObserver: forKeyPath: context:' – titaniumdecoy

+0

Tôi thường đặt '-removeObserver: forKeyPath: context:' trong phương thức '-dealloc'. –

0

Đối với những người không thích KVO:

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

Yeah, chỉ cần sử dụng super để truy cập phương pháp cha mẹ. Điều này giả sử bạn phân lớp UIScrollview/TableView/CollectionView