Tuesday, April 12, 2011

[self.tableView setContentOffSet:] does not work

In the iPhone app I'm developing these days there was this instance where I was required to have a search box on top of a table view and to show/hide when required.

When the page loads I didn't want it, so I added the following in the view will appear method.

[self.tableView setContentOffset:CGPointMake(0, 44) animated:FALSE];

44 = height of the view/searchbox at the top of the table view

User could see it when he/she pull the table view down. I wanted away to hide it when the user pushes the table view up. So in the scrollViewDidEndDragging delegate method I tried calling the set content offset method. But this worked only when I had my view filled with cells. When the table view contains only one or two cells this didn't work. So I had to check the table view content height and set it pragmatically and then set the offset. So the final code looked liked the following

if ([self.tableView contentSize].height < 460) { [self.tableView setContentSize:CGSizeMake(320, 460)]; [self.tableView setContentOffset:CGPointMake(0, 44) animated:FALSE]; }else { [self.tableView setContentOffset:CGPointMake(0, 44) animated:FALSE]; } But before you used this inside the scrollViewDidEndDragging delegate method you need to check scroll view's content offset to identify whether the user really wants to hide the search. You can check this in the following way, CGPoint point = scrollView.contentOffset ; if ((point.y > 22) && (point.y < 44)) {

if ([self.tableView contentSize].height < 460) {


[self.tableView setContentSize:CGSizeMake(320, 460)];

[self.tableView setContentOffset:CGPointMake(0, 44) animated:FALSE];

}else {

[self.tableView setContentOffset:CGPointMake(0, 44) animated:FALSE];

}
}

No comments: