0

I am newbie to iOS/Swift. I am developing app using Swift4 on XCode12. But I have a problem with presenting UIViewController.

Below is my code:

import UIKit
import CoreGraphics

class NewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        let cancelButton = UIButton()
        
        cancelButton.frame = CGRect(
            x: view.frame.width/2 - 30,
            y: view.frame.height - 120,
            width: 60,
            height: 44)
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.backgroundColor = UIColor.systemGreen
        cancelButton.contentMode = .scaleAspectFit
        view.addSubview(cancelButton)
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let n1 = NewController()
        //self.navigationController?.pushViewController(n1, animated: true)
        self.present(n1, animated: true, completion: nil)
    }
}

But it shows like this image. Image before/after presenting

As you can see in the image, it shows black margin after presenting NewController.

Anybody can help me?

I tested on simulator iPhone 8 (iOS 14.2).

Aliaksandr
  • 35
  • 7
  • You can't create a new `NewController()` like that... got to [instantiate from storyboard](https://stackoverflow.com/a/24036067/14351818). – aheze Jun 24 '21 at 21:17
  • @aheze you can create ViewControllers programmatically, you don’t need to instantiate from storyboards. – Andrew Jun 24 '21 at 21:34
  • @Andrew but OP didn't override the `loadView` method, I thought you needed that for programmatic vc? – aheze Jun 24 '21 at 21:46
  • Wait... I see, nvm – aheze Jun 24 '21 at 21:48

1 Answers1

0

Please review below code / comments.

class NewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add any color so you can clearly identify this
        self.view.backgroundColor = .yellow
    }

    override func viewDidAppear(_ animated: Bool) {
        // In your code this call is missing, do not miss this
        super.viewDidAppear(animated)
        
        // Rest of your code.
    }

}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add any color so you can clearly identify this
        self.view.backgroundColor = .red
    }
    
    override func viewDidAppear(_ animated: Bool) {
        // In your code this call is missing, do not miss this
        super.viewDidAppear(animated)

        let n1 = NewController()
        self.present(n1, animated: true, completion: nil)
    }
}
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • Thanks for your answer. I solved it with by adding this line. `n1.modalPresentationStyle = .overFullScreen` – Aliaksandr Jun 24 '21 at 21:21