I have a UIView with a grouped UITableView and I’d like the UIView to stay as a fixed tableHeaderView, rather than moving when scrolling the UITableViewCell‘s. Therefore I’d like the cells to be behind the UIView when scrolling.
This is the code I’m currently using to add my UIView to my UIViewController:
Interface.h:
@interface MyAccountVC : UIViewController <UITableViewDelegate, UITableViewDataSource> {
HeaderView *myHeaderView; // Inherits from UIView
UITableView *tv;
}
@property (nonatomic, retain) IBOutlet UITableView *tv;
@property (nonatomic, retain) HeaderView myHeaderView;
Implementation.m (in viewDidLoad):
// Set up the table's header view based on our UIView 'HeaderView' outlet.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UIView class]]) {
self.myHeaderView = (HeaderView *)currentObject;
break;
}
}
CGRect newFrame = CGRectMake(0.0, 0.0, self.tv.bounds.size.width, self.myHeaderView.frame.size.height);
self.myHeaderView.frame = newFrame;
self.tv.tableHeaderView = self.myHeaderView;
Not sure if this is the best way of adding myHeaderView to the UITableView, but it seems to be working fine and I can simply add the above code to any UIViewController with a UITableView to re-use the header if need be.
At the moment the header moves with the cells as I scroll, but I’d like the header to be fixed just below the top UINavigationBar while the cells move freely and behind the header. Please let me know if this all makes sense or whether you need more code in order to determine what I am trying to achieve.
Just elaborating on Paramasivan’s answer.
I don’t create views with nib files, so I will describe the code assuming you create views programmatically.
What you need to do is, just place header view at the top, and place a sized tableview below top.
Example:
This way, you have a UIView that’s always at the top of the view, and won’t scroll with tableview.
If you add myHeaderView to be the tableview headerView, it will always scroll with the tableview I think.
In your example, using nib, you can probably resize the frame in the “viewDidLoad” function so that UITableView starts at position (0, myHeaderView.frame.size.height).
EDIT* finally figured out how to use 4 spaces for code formatting 🙂