5

I have a page view controller with 3 pages. I want a 'floating' button to be visible on top of all of them. I have tried using a container view for the PageView but that doesn't seem to work. How else can I get the button to remain visible across all 3 pages?

I have tried using a container view as stated in this question: UIButton across all pages of UIPageViewController

Will Taylor
  • 511
  • 1
  • 6
  • 14
  • See https://stackoverflow.com/a/40380171/6448167 for an example of how to add a floating button on screen – KSigWyatt Sep 05 '18 at 18:09

2 Answers2

2

You can create a separate ViewController, add a container view, ctrl-click and drag to your pageViewController and click "Embed". Add any buttons to your new separate ViewController and associate the ViewController with a new swift class, and manage your button functions there.

If your pageViewController is currently your initial ViewController (or root view if you are using a navigation controller), you simply change it so that the separate ViewController is now the initial viewController, containing the embedded PageViewController, and any buttons that you need. When you scroll, they will remain stationary on top of the view.

If you are using Storyboard, it should look something like this:

enter image description here

Peter Ruppert
  • 1,067
  • 9
  • 24
2

Alternatively to my other answer, you can add a button programmatically.

Declare:

let button = UIButton()

and if you want, create a function called setupView()

private func setupView() {

//Here we set up the size and attributes of the button.
    currencyButton.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
    currencyButton.backgroundColor = UIColor.red
    currencyButton.setTitle("YourButtonTitle", for: .normal)
    currencyButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    self.view.addSubview(currencyButton)
}

And to use the button:

@objc func buttonAction(sender: UIButton!) {
   //Do whatever.
   print("ButtonTapped")
}

Finally, make sure that in viewDidLoad() setupView() is called:

 override func viewDidLoad() {
    super.viewDidLoad()

    setupView()

    self.delegate = self
    configurePageControl()
    self.dataSource = self

}

This button will stay on screen when you scroll through the page view. Let me know if this answers your question.

Peter Ruppert
  • 1,067
  • 9
  • 24