iPhone UITableView with a header area

前端 未结 8 917
礼貌的吻别
礼貌的吻别 2020-12-23 20:26

I have a view that was created with all of the default UITableView stuff, but now I need to add a header area above where the UITableView is (so th

8条回答
  •  隐瞒了意图╮
    2020-12-23 20:43

    I finally solved this problem the right way without changing the base class. The one answer to add the view to the parent nav controller is nice but the transitions look horrible.

    The fix is actually easy. The trick is to create custom setter and getter for self.tableView property. Then, in loadView, you replace the view with a fresh UIView and add the tableView to it. Then you're free to add subviews around the tableView. Here's how it's done:

    In header:

    @interface CustomTableViewController : UITableViewController
    {
        UITableView *tableView;
    } 
    

    In .m:

    - (UITableView*)tableView
    {
        return tableView;
    }
    
    - (void)setTableView:(UITableView *)newTableView
    {
        if ( newTableView != tableView )
        {
            [tableView release];
            tableView = [newTableView retain];
        }        
    }
    
    - (void)loadView {
        [super loadView];
        //save current tableview, then replace view with a regular uiview
        self.tableView = (UITableView*)self.view;
        self.view = [[UIView alloc] initWithFrame:self.tableView.frame];
        [self.view addSubview:self.tableView];    
    
        //code below adds some custom stuff above the table
        UIView *customHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
        customHeader.backgroundColor = [UIColor redColor];
        [self.view addSubview:customHeader];
        [customHeader release];
    
        self.tableView.frame = CGRectMake(0, customHeader.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - customHeader.frame.size.height);
    }
    
    - (void)viewDidUnload
    {
        self.tableView = nil;
        [super viewDidUnload];
    }
    

    Enjoy!

提交回复
热议问题