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)
}
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With