Search code examples
swiftxcodeipaduibuttonframe

How to set a button's width based on an iPad Modal View Controller's frame width? - Swift 5


so I'm trying to add a button that is the view's width - 50 and have it be centered in the lower portion of the view controller.

This is how I am doing that:

    purchaseButton.layer.cornerRadius = 14
    purchaseButton.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 50, height: 50)
    purchaseButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
    purchaseButton.contentEdgeInsets = UIEdgeInsets(top: 14, left: 0, bottom: 14, right: 0)
    let xPosition: CGFloat = self.view.frame.width / 2.0
    let yPosition: CGFloat = self.view.frame.height / 1.25
    purchaseButton.center = CGPoint(x: xPosition, y: yPosition)

This works perfectly on all iPhone devices and sizes. However, for an iPad the view is a modal and I think the frame.width is the entire iPad screen size instead of just the smaller view. This causes the button to be too low and too wide on iPad devices. Is there any way I can get the width and height of the modal popover view controller instead of the entire device's frame and use that to set the button size?


Solution

  • I found out that I need to call the code in viewWillAppear rather than viewDidLoad in order to get the correct size of the view controller. Doing so fixed the issue!