Search code examples
swiftviewconstraintsnslayoutconstraint

How to constrain an object to full screen


I want to know how to code an imageview to the full screen programmatically. Right now I know how to code an object to a specific size and position programmatically but I want to know how to get this object in the full screen no matter what device is being used.

FIRE.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
FIRE.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true

FIRE.widthAnchor.constraint(equalToConstant: 400).isActive = true
FIRE.heightAnchor.constraint(equalToConstant: 700).isActive = true
FIRE.translatesAutoresizingMaskIntoConstraints = false

Solution

  • I'm assuming your object is FIRE and the parent view is view. You can do it with constraints as follows.

    FIRE.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    FIRE.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
    FIRE.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    FIRE.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    FIRE.translatesAutoresizingMaskIntoConstraints = false
    

    Or you could do it using the auto-resizing mask

    FIRE.frame = view.bounds
    FIRE.autoresizingMask = [.flexibleWidth, .flexibleHeight]