When Google released Material Design Guidelines they introduced many new design elements and one of them was Fab Button i.e. Floating Action Button
Normally we see the Fab button in Android Mobile Apps but a lot of Apple iPhone, iPad and Mac App Developers has started using the Fab button in their design.
Here we will see how to add the Fab button programmatically in your iOS, iPadOS and macOS app on any view including UICollectionView or UITableView.
Step 01: First declare the UIButton variable in your View Controller
var fabButton = UIButton()
Step 02: Add this code to viewDidLoad()
override func viewDidLoad() { super.viewDidLoad() self.fabButton = UIButton(type: .custom) self.fabButton.addTarget(self, action: #selector(self.addDataFabButton(_:)), for: UIControl.Event.touchUpInside) self.view.addSubview(self.fabButton) }
Step 03: Add this function to your View Controller that will get called by the code that we added in viewDidLoad()
@IBAction func addDataFabButton(_ sender: UIButton){ print("Fab Button Clicked") // Write your code here }
Step 04: Now add this code in your viewWillLayoutSubviews() to display the Fab button in your app
override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() fabButton.layer.cornerRadius = 30 fabButton.backgroundColor = UIColor.red fabButton.clipsToBounds = true let symbolConfig = UIImage.SymbolConfiguration(pointSize: 30.0, weight: .regular, scale: .medium) let symbol = UIImage(systemName: "plus", withConfiguration: symbolConfig)?.withTintColor(.white, renderingMode: .alwaysOriginal) fabButton.setImage(symbol, for: .normal) fabButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ fabButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20), fabButton.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20), fabButton.widthAnchor.constraint(equalToConstant: 60), fabButton.heightAnchor.constraint(equalToConstant: 60) ]) }
I hope this blog post helps you to code the Fab button in your iPhone, iPad and Mac app.
Reference: I referred to this post from Stack overflow for an answer
Thanks & Regards
Mandar Apte