Following @ Kunal Kumar's answer, it works with UIScrollView and UIView , but it does not work on UITableView . I found it easy to work with a UITableView , you only need to add one line code. Thank you so much @Kunal Kumar
in viewDidLoad , change self.view.addSubview(roundButton) to self.navigationController?.view.addSubview(roundButton) and it will work!
By the way, I think we need to add super.viewWillLayoutSubviews() to the viewWillLayoutSubviews() method.
below is all the code mentioned above
Swift 3
// MARK: Floating Button var roundButton = UIButton() func createFloatingButton() { self.roundButton = UIButton(type: .custom) self.roundButton.setTitleColor(UIColor.orange, for: .normal) self.roundButton.addTarget(self, action: #selector(ButtonClick(_:)), for: UIControlEvents.touchUpInside) //change view to navigationController?.view, if you have a navigationController in this tableview self.navigationController?.view.addSubview(roundButton) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2 roundButton.backgroundColor = UIColor.lightGray roundButton.clipsToBounds = true roundButton.setImage(UIImage(named:"ic_wb_sunny_48pt"), for: .normal) roundButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -3), roundButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -53), roundButton.widthAnchor.constraint(equalToConstant: 50), roundButton.heightAnchor.constraint(equalToConstant: 50)]) }
source share