My code is not compiling when I am using NSLayoutConstraint. I am trying to do everything with code and not using storyboard. I dont know if this is happening because I am missing something but it is nothining I can think of right now of why this is not working. The error is occurring in the viewDidLoad function at the judo = line
.
I am getting the error:
Cannot assign value of type '[()]' to type '[NSLayout
for the judo = []
part.
import UIKit
class ViewController: UIViewController {
var Judo1 = [NSLayoutConstraint]()
let FIRE = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(FIRE)
FIRE.translatesAutoresizingMaskIntoConstraints = false
let leadingc2 = FIRE.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
let trailingC2 = FIRE.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
let topc2 =
FIRE.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
let bottomc2 = FIRE.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
Judo1 = [leadingc2,trailingC2,topc2,bottomc2]
NSLayoutConstraint.activate(Judo1)
}
}
When you append
.active = true
no constraint returns so make them without .active = true
as the return is void in this case
FIRE.translatesAutoresizingMaskIntoConstraints = false
let leadingc2 = FIRE.topAnchor.constraint(equalTo: view.topAnchor, constant: 0)
let trailingC2 = FIRE.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
let topc2 = FIRE.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0)
let bottomc2 = FIRE.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0)
judo1 = [leadingc2,trailingC2,topc2,bottomc2]
NSLayoutConstraint.activate(judo1)
A better way to use what apple recommends ( if you don't need a reference )
NSLayoutConstraint.activate ([
FIRE.topAnchor.constraint(equalTo: view.topAnchor),
FIRE.bottomAnchor.constraint(equalTo: view.bottomAnchor),
FIRE.leadingAnchor.constraint(equalTo: view.leadingAnchor),
FIRE.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
Also when constant is zero , get rid of it