0

I have used ObjC, and xib for years, now moving to Swift/Autolayout, I got a very stupid mistake, I have a hello world app with a button, Autolayout is set to show button on the middle of the screen X n Y

enter image description here

When I try "View as:" it shows in the middle for all screens iPhone 7p, 7, SE, 4S... it shows the button in the middle. But the button is not showing on my modal ViewController

Here how I show it,

@IBAction func buttonPresse(_ sender: AnyObject) {
    let modalViewController = Modal1ViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    present(modalViewController, animated: true, completion: nil)
}

And this to color background on shown modal

override func viewDidLoad() {
    super.viewDidLoad()        
    view.backgroundColor = UIColor.green
    view.isOpaque = false
}

Thats all!, why is my button not showing :/ thx!

Nirav D
  • 71,513
  • 12
  • 161
  • 183
manuelBetancurt
  • 15,428
  • 33
  • 118
  • 216

3 Answers3

2

The problem you are facing is because you are present the new empty instance using Modal1ViewController() instead of that you need to create instance from storyboard using instantiateViewController(withIdentifier:). So try like this.

let modalViewController = self.storyboard?.instantiateViewController(withIdentifier: "Modal1ViewController") as! Modal1ViewController
modalViewController?.modalPresentationStyle = .overCurrentContext
present(modalViewController!, animated: true, completion: nil)

Note: For this you need to set Storyboard ID with your Modal1ViewController, if you doesn't know how to set Storyboard ID check this link, set the identifier like this question does.

Community
  • 1
  • 1
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

When we create a UI using auto-layout then we need to initialize it with the storyboard because storyboard holds the layouts and framing for subviews so If we initialize it without the reference of storyboard or Xib, only instance were created and layout is not set by own self.

Objective-C :-

Modal1ViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"identifier"];

Swift :-

let vc = self.storyboard?.instantiateViewController(withIdentifier: "identifier") as! Modal1ViewController
Avineet Gupta
  • 586
  • 10
  • 21
1

If you don't want to perform any extra task on button click of previous screen, then you can directly use segue to redirect to screen and then set Presentation property of your UIViewController to Over Current Context from attribute inspector. So you don't have to do all this stuff.

Drag mouse pointer with right click pressed or press control key and drag mouse left key from button to second screen

Give segue from button to second screen

Then select Show option

Select Show from popup to assign segue

Then open Attribute Inspector and change as shown below

UIVIewController Attribute Inspector

Dhaval Dobariya
  • 171
  • 1
  • 12