How to add a UIView above the current UITableViewController

后端 未结 20 814
旧时难觅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条回答
  •  Happy的楠姐
    2020-11-27 12:41

    Solution for swift (equivalent to Daniel Saidi):

    If your controller is a UITableViewController in a Storyboard or XIB and you wish to reassign self.view to a standard UIView while preserving your existing table view:

    @IBOutlet var tableViewReference: UITableView!
    var viewReference: UIView!
    

    Then in your implementation file:

    Add these instance variables to your table view controller file:

    override var tableView: UITableView! {
        get { return tableViewReference }
        set { super.tableView = newValue }
    }
    
    override var view: UIView! {
        get { return viewReference }
        set { super.view = newValue }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.edgesForExtendedLayout = UIRectEdge.None
        self.extendedLayoutIncludesOpaqueBars = false
        self.automaticallyAdjustsScrollViewInsets = false
    
        //rewiring views due to add tableView as subview to superview
        viewReference = UIView.init(frame: tableViewReference.frame)
        viewReference.backgroundColor = tableViewReference.backgroundColor
        viewReference.autoresizingMask = tableViewReference.autoresizingMask
        viewReference.addSubview(tableViewReference)
    }
    

    In your Storyboard or XIB file: Connect the tableView in the UITableViewController to the tableViewReference variable.

    Then you will be able to add child views as follows:

    self.view.addSubView(someView)
    

提交回复
热议问题