How to add a UIView above the current UITableViewController

后端 未结 20 851
旧时难觅i
旧时难觅i 2020-11-27 11:57

I have difficulty adding a subview (UIView) from within the viewDidLoad method of a UITableViewController

This works:

[self.view addSubview:self.prog         


        
20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 12:32

    The problem is that the view property of UITableViewController is identical to the tableView property. What this means is that the root view is always a table view controller, and anything added as a subview will be subject to the table view functionality. This has other undesirable side effects, like your subviews scrolling when you may not want them to.

    There are a couple options here. You could override loadView and install your own view and table view:

    // note: untested
    - (void)loadView {
        self.view = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
        self.view.backgroundColor = [UIColor whiteColor];
    
        UITableView *tblView = [[UITableView alloc]
            initWithFrame:CGRectZero
            style:UITableViewStylePlain
        ];
    
        tblView.autoresizingMask =
            UIViewAutoresizingFlexibleWidth |
            UIViewAutoresizingFlexibleHeight
        ;
    
        self.tableView = tblView;
        [self.view addSubview:tblView];
        [tblView release];
    }
    

    And then when you need to add a subview, add it below or above self.tableView as appropriate.

    Another option is just to create a UIViewController subclass that does what you need. UITableViewController honestly doesn't add that much, and the little functionality it does implement is easily replicated. There are articles like Recreating UITableViewController to increase code reuse that explain how to do this pretty easily.

提交回复
热议问题