IOS-如何将视频添加为ViewController背景并使用swift在运行时添加约束

时间:2014-12-21 12:44:55

标签: ios iphone video swift viewcontroller

我想为我的iphone应用创建一个具有视频背景的登录屏幕。 查看this sample以获取概念参考。

问:有什么类似UIImageView可以播放视频吗? 什么是正确的方法?

修改

我设法添加视频并将其缩放以适应视图,但是当我旋转设备时视频被裁剪。

代码:

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()

}

尝试在运行时添加约束但失败了。

如何添加在设备旋转时保持全屏视图的约束?

1 个答案:

答案 0 :(得分:1)

我添加了以下约束并且它有效。只需将moviePlayer视图居中,其宽度和高度等于其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)