Search code examples
iosswiftautolayout

Auto Layout - How to add a subview to match the size of a UIView?


I am stuck on a issue I have encountering with Auto Layout. I have a UIView that has constraints set so it is in the same position for every size class. I am trying to get my video to fit perfectly inside of this UIView videoViewBox. I got it working on iPhone 6 only, but if I switch to iPhone 4S/5, the video is no longer aligned.

This is the code:

    var moviePlayer: MPMoviePlayerController!

    @IBOutlet var videoViewBox: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let path = NSBundle.mainBundle().pathForResource("tutorial", ofType: "mov")
        let url = NSURL.fileURLWithPath(path!)
        moviePlayer = MPMoviePlayerController(contentURL: url)
        moviePlayer.view.frame = CGRect(x: 10, y: 50, width: 255, height: 400)
        videoViewBox.addSubview(moviePlayer.view)

        moviePlayer.fullscreen = true
        moviePlayer.controlStyle = MPMovieControlStyle.None
    }

I tried setting the values of CGRect dynamically with the values from videoViewBox.frame.origin.x and videoViewBox.frame.origin.y, but it wasn't aligned either.

How would I go about doing this? Thanks for helping!


Solution

  • Don't set the frame for the moviePlayer view. Instead, add Autolayout constraints to constrain the moviePlayer view to its superview. You can do this using the Visual Format:

    moviePlayer.view.translatesAutoresizingMaskIntoConstraints = false
    videoViewBox.addSubview(moviePlayer.view)
    
    let views = ["moviePlayerView": moviePlayer.view]
    
    let hconstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[moviePlayerView]|", metrics: nil, views: views)
    NSLayoutConstraint.activate(hconstraints)
    
    let vconstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[moviePlayerView]|", metrics: nil, views: views)
    NSLayoutConstraint.activate(vconstraints)
    

    Alternatively, you can use anchors:

    moviePlayer.view.translatesAutoresizingMaskIntoConstraints = false
    videoViewBox.addSubview(moviePlayer.view)
    
    moviePlayer.view.topAnchor.constraint(equalTo: videoViewBox.topAnchor).isActive = true
    moviePlayer.view.bottomAnchor.constraint(equalTo: videoViewBox.bottomAnchor).isActive = true
    moviePlayer.view.leadingAnchor.constraint(equalTo: videoViewBox.leadingAnchor).isActive = true
    moviePlayer.view.trailingAnchor.constraint(equalTo: videoViewBox.trailingAnchor).isActive = true