jpatrick
jpatrick

Reputation: 43

Swift: Adding floating button to TableViewController?

I'm having trouble at TableViewController. I want to add floating button, but I found out that if I create tableview with TableviewController in Storyboard, then tableview is superview in that view controller, which means only way to add button is adding button in tableview as one of a cell, which is not floating button. (Maybe I'm wrong. I'm a bit confused. I can't add another view by Storyboard.) I googled several times and I think the only solution is to add button by using UIWindow, but part of the solution codes are deprecated. I hope I can get alternate solution for my problem.

Upvotes: 1

Views: 646

Answers (1)

Mr.SwiftOak
Mr.SwiftOak

Reputation: 1844

Obviously the best solution is using UIViewController and adding UITableView and your button as subviews (as @Surjeet Singh suggested in comment). However if you face troubles doing this (maybe too complex right now), you can add UIButton as subview of your keyWindow as workaround. however keep in mind that you need to manually remove the button from keyWindow once your UITableViewController is going to disappear, or else your button will be appearing on other UIViewControllers. Here is the workaround solution:

    func addFloatingButton() {
    let keyWindow = UIApplication.shared.keyWindow
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    button.backgroundColor = .red
    keyWindow?.addSubview(button)
}

Upvotes: 1

Related Questions