Add button on top of UITableViewController (Swift)

前端 未结 8 1073
夕颜
夕颜 2021-02-07 15:34

I am trying to add a button ontop of a uitableview controller table view. The view controller has a navigation controller and static cells, which is why it is a uitableviewcontr

8条回答
  •  不思量自难忘°
    2021-02-07 16:04

    Unfortunately UITableViewController has a tableView as its top level view. Of course if you look in the view debugger you can see that the tableview is not the root view. Therefore you can add the buttons to the tableView's window programatically. If you have to do it after the fact, this is probably the easiest way to add a top level element over a UITableViewController. Otherwise if you are doing it in the initial design, you can use container view for your buttons and a UITableViewController for the TableView. The downside of this approach is you end up with two view controllers, one for the container and one for the table and its often necessary to pass information back and for between them. If you are using swift you can simplify this by nesting the tableViewcontroller inside the container view controller class.

    If you want to add a button to the window, you can do this lazily once you are sure that the view has a window. Note that the buttons belong to the window and not to the view controller, so its your responsibility to remove them when the view controller disappears.

        private weak var button: UIButton!
        ...
        override func didMove(toParentViewController parent: UIViewController?) {
            super.didMove(toParentViewController: parent)
            guard self.button == nil, let window = tableView.window else {
                return
            }
            let button = UIButton(frame: CGRect(x:0, y:40, width: 200, height: 20))
            button.setTitle("This is a red button", for: .normal)
            button.backgroundColor = UIColor.red
            window.addSubview(button)
            self.button = button
        }
    
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            button?.removeFromSuperview()
        }
    

提交回复
热议问题