I met the same issue, put ui code and its constraints inside viewDidLoad
into loadView()
fix it. Now the animation is moving smoothly.
Refer here: https://stackoverflow.com/a/3424052/10158398
loadView is the method that actually sets up your view (sets up all
the outlets, including self.view).
viewDidLoad you can figure out by its name. It's a delegate method
called after the view has been loaded (all the outlets have been set)
that just notifies the controller that it can now start using the
outlets.
viewDidLoad: "This method is called after the view controller has
loaded its associated views into memory. This method is called
regardless of whether the views were stored in a nib file or created
programmatically in the loadView method."
loadView: "If you create your views manually, you must override this
method and use it to create your views."
For an example:
class DetailViewController: UIViewController {
let imageView = UIImageView()
var picture: Picture?
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
view = UIView()
view.backgroundColor = .white
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
if let picture = picture {
let path = getDocumentDirectory().appendingPathComponent(picture.picture)
imageView.image = UIImage(contentsOfFile: path.path)
}
}