Tuesday, May 6, 2014

ios/xcode: membuat pull to refresh scroll ke atas

Pull to refresh, sebagaimana yang lazim adalah user scroll table view ke bawah baru kemudian table view akan direfresh. Namun ada kalanya yang namanya user itu mintanya aneh-aneh dan ngeyelan. Dibilangin lazimnya seperti itu tetap saja tidak mau, maunya table view di scroll ke atas kemudian kalau table view sudah mentok atas akan ter-refresh. Bagaimana membuat seperti itu?

ios pull to refresh scroll up



Untuk membuat pull to refresh yang normal (scroll ke bawah) anda bisa menggunakan refresh controller (UIRefreshControl). Namun controller ini tidak bisa anda modifikasi untuk membuat refresh ketika scroll ke atas. Tapi anda bisa mengakalinya dengan menggunakan method scrollViewDidScroll. Berikut snippet codingnya.

 
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {

CGPoint offset = aScrollView.contentOffset;

CGRect bounds = aScrollView.bounds;

CGSize size = aScrollView.contentSize;

UIEdgeInsets inset = aScrollView.contentInset;

float y = offset.y + bounds.size.height - inset.bottom;

float h = size.height;

// NSLog(@”offset: %f”, offset.y);

// NSLog(@”content.height: %f”, size.height);

// NSLog(@”bounds.height: %f”, bounds.size.height);

// NSLog(@”inset.top: %f”, inset.top);

// NSLog(@”inset.bottom: %f”, inset.bottom);

// NSLog(@”pos: %f of %f”, y, h);

float reload_distance = 10;

if(y > h + reload_distance) {

if (isReloading==NO) {
NSLog(@"load more rows");
isReloading = YES;
[self pullBottomToRefresh];
}

}

}

Ketika anda melakukan scroll ke atas dan table view sudah sampai pada row terakhir maka method pullBottomToRefresh akan terpanggil. Parameter isReloading di atas dipakai agar method pullBottomToRefresh tidak terpanggil berulang-ulang.

No comments:

Post a Comment