Add button on top of UITableViewController (Swift)

前端 未结 8 2008
盖世英雄少女心
盖世英雄少女心 2021-02-07 16:02

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:27

    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()
        }
    
    0 讨论(0)
  • 2021-02-07 16:28

    Here is a UIViewController, with a UITableView added as a subview. At the top right, you can see a dropdown that says Content: Dynamic Prototypes. Change it to Static Cells. enter image description here

    0 讨论(0)
提交回复
热议问题