Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a floating action button on UITableView in Swift

I'm trying to add a floating action button (not a floating menu button) which will navigate me to the next view controller with a single click. I'm not getting the floating button right. I have tried the below code and it is not showing the appropriate button on the table view as it is getting scrolled along with the table. Is there any way to stick the button at the same place without getting scrolled along with the table?

func floatingButton(){
    let btn = UIButton(type: .custom)
    btn.frame = CGRect(x: 285, y: 485, width: 100, height: 100)
    btn.setTitle("All Defects", for: .normal)
    btn.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
    btn.clipsToBounds = true
    btn.layer.cornerRadius = 50
    btn.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    btn.layer.borderWidth = 3.0
    btn.addTarget(self,action: #selector(DestinationVC.buttonTapped), for: UIControlEvent.touchUpInside)
    view.addSubview(btn)
}

enter image description here

like image 311
Saurabh Avatar asked Jan 17 '18 10:01

Saurabh


1 Answers

All subviews added to UITableView will automatically scroll with it.

What you can do is add the button to the application Window, just remember to remove it when the ViewController disappears.

var btn = UIButton(type: .custom)
func floatingButton(){
    btn.frame = CGRect(x: 285, y: 485, width: 100, height: 100)
    btn.setTitle("All Defects", for: .normal)
    btn.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
    btn.clipsToBounds = true
    btn.layer.cornerRadius = 50
    btn.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    btn.layer.borderWidth = 3.0
    btn.addTarget(self,action: #selector(DestinationVC.buttonTapped), for: UIControlEvent.touchUpInside)
    if let window = UIApplication.shared.keyWindow {
        window.addSubview(btn)
    }
}

and in viewWillDisappear:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    btn.removeFromSuperview()
}

For iOS 13 and above you can check for the key window using this extension:

extension UIWindow {
    static var key: UIWindow? {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.first { $0.isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}
like image 108
ahbou Avatar answered Oct 15 '22 11:10

ahbou