简体   繁体   中英

IOS - Keep UIView on top of UITableView on scroll

I have a UITableView with a UIView on top. I want the UIView to stick to the top as the tableView cells scroll over it.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.tableView.contentOffset.y > 0) {
        CGRect newframe = self.publicTopView.frame;
        newframe.origin.y = -self.tableView.contentOffset.y;
        self.publicTopView.frame = newframe;
        NSLog(@"After: %f", self.publicTopView.frame.origin.y);
    }
}

You need to set your table view header view to the view you want on top.

Add this code to you viewDidLoad

self.tableView.tableHeaderView = self.publicTopView

I'm not certain what you're trying to accomplish, but I have a guess at what is wrong. As you scroll your contentOffset will continue to change and let's say your tableView has a content size height of 1500, then your contentOffset will eventually be larger than the height of your view controllers view. Now see that you are putting that contentOffset into the origin.y of your publicTopView . So your publicTopView could possibly be moving too much, even offscreen depending on how large your tableview's content size is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM