I'm new to swift and I'm trying to make an app that will just be a background and a button that when pressed will make a second view with another background appear I got the code for the UIImage from https://youtu.be/4wodsPzFHQk
import UIKit
import PlaygroundSupport
final class MyViewController: UIViewController {
override func loadView() {
let view = UIView()
let BG = UIImageView(frame: UIScreen.main.bounds)
BG.image = UIImage(named:"Photo.png")
BG.contentMode = .scaleAspectFill
BG.insertSubview(view, at:0)
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = MyViewController()
The problem is that when I run the code with the function step through my code I see that the code from
override func loadView() to BG.insertSubview(view, at:0) is ran multiple times.
Thanks for any help in advance
CodePudding user response:
From the loadView() documentation:
The view controller calls this method when its
viewproperty is requested but is currentlynil. This method loads or creates a view and assigns it to theviewproperty.
Since the loadView implementation in MyViewController never assigns the view property, it remains nil which means that the next time the view property is accessed, loadView is called again.
To fix this you would add self.view = view at the end of the loadView implementation.
