How to add a UIView above the current UITableViewController

后端 未结 20 850
旧时难觅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:46

    To add a customView above the current UITableViewController, it must be a nice way to use 'self.navigationController.view addSubview:customView' like Daniel commented.

    However, in case of implementing customView that serves as navigationBar, Daniel's way can cause unexpected result to default or custom navigationBar on other navigationViewControllers that is in front and back of the UITableViewController.

    The best simple way is just converting UITableViewController into UIViewController which has no limit on layout it's subviews. But, if you're struggling with massive, long legacy UITableViewController code, the story is totally different. We don't have any sec for converting.

    In this case, you can simply highjack tableView of UITableViewController and solve this whole problem.

    The most important thing we should know is UITableViewController's 'self.view.superview' is nil, and 'self.view' is UITableView itself.

    First, highjack the UITableVIew.

    UITableView *tableView = self.tableView;
    

    Then, replace 'self.view'(which is now UITableView) with a new UIView so that we can layout customViews with no-limitation.

    UIView *newView = UIView.new;
    newView.frame = tableView.frame;
    self.view = newView;
    

    Then, put UITableView we highjacked before on the new self.view.

    [newView addSubview:tableView];
    tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [tableView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
    [tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
    [tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
    [tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
    

    Now, we can do whatever we want on this brand new fancy 'self.view' on UITableViewController.

    Bring a custom View, and just add as subView.

    UIView *myNaviBar = UIView.new;
    [myNaviBar setBackgroundColor:UIColor.cyanColor];
    [self.view addSubview:myNaviBar];
    
    myNaviBar.translatesAutoresizingMaskIntoConstraints = NO;
    [myNaviBar.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
    [myNaviBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
    [myNaviBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
    [myNaviBar.heightAnchor constraintEqualToConstant:90].active = YES;
    

    gif

提交回复
热议问题