Shlomi Schwartz
Shlomi Schwartz

Reputation: 8903

IOS- How to add a video as a ViewController background and add constraints at runtime using swift

I would like to create a login screen for my iphone app that will have a video background. check out this sample for a concept reference.

Q: Is there anything similar to UIImageView that can play video? What would be the correct approach?

EDIT

I've managed to add the video and scale it to fit the view, however I when I rotate the device the video is cropped.

Code:

override func viewDidLoad() {
    super.viewDidLoad()

    var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!

    moviePlayer = MPMoviePlayerController(contentURL: url)
    moviePlayer.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

    moviePlayer.controlStyle = MPMovieControlStyle.None
    moviePlayer.scalingMode = MPMovieScalingMode.AspectFill

    self.view.insertSubview(moviePlayer.view, atIndex: 0)
    moviePlayer.play()

}

Tried adding constraints at runtime but failed.

How can I add constraints that will keep the full screen view when device is rotated?

Upvotes: 1

Views: 540

Answers (1)

gabbler
gabbler

Reputation: 13766

I added the following constraints and it worked. Just make the moviePlayer view centered and its width and height equal to that of its superview.

theView.setTranslatesAutoresizingMaskIntoConstraints(false)

var constX = NSLayoutConstraint(item: theView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(constX)

var constY = NSLayoutConstraint(item: theView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(constY)

var constW = NSLayoutConstraint(item: theView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
view.addConstraint(constW)

var constH = NSLayoutConstraint(item: theView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
view.addConstraint(constH)

Upvotes: 1

Related Questions