2015-05-12 7 views
1

Я застрял в проблеме, с которой я сталкиваюсь с автоматической компоновкой. У меня есть UIView, у которого есть ограничения, установленные таким образом, чтобы они находились в одном и том же положении для каждого класса. Я пытаюсь получить мое видео, чтобы он идеально вписывался в это UIViewvideoViewBox. Я получил его работу только на iPhone 6, но если я переключусь на iPhone 4S/5, видео больше не будет выровнено.Auto Layout - Как добавить subview в соответствии с размером UIView?

Это код:

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 
    } 

Я попытался установить значения CGRect динамически со значениями из videoViewBox.frame.origin.x и videoViewBox.frame.origin.y, но он не был приведен в соответствие либо.

Как бы я это сделал? Спасибо за помощь!

ответ

3

Не устанавливайте рамку для просмотра фильма. Вместо этого добавьте ограничения Autolayout, чтобы ограничить представление moviePlayer своим супервизором. Вы можете сделать это с помощью визуального Формат:

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) 

В качестве альтернативы, вы можете использовать якоря:

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 
+0

Спасибо вам большое, проще, чем я думал! – Jordan

0

Вы должны использовать AutoLayoutConstrains для достижения этой цели.

Вы можете оба применить эти ограничения непосредственно к своей раскадровке или по коду. Я предполагаю, что вы хотите сделать это с помощью кода. В этом случае это должен быть путь:

let path = NSBundle.mainBundle().pathForResource("tutorial", ofType: "mov") 
let url = NSURL.fileURLWithPath(path!) 

moviePlayer = MPMoviePlayerController(contentURL: url) 
let movieView = moviePlayer.view! 

//this will be the height of your control 
var heightValue: CGFloat = 400 

//This will leave a marging of 50 on top 
var top = NSLayoutConstraint(item: movieView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: videoViewBox, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 50) 
//This will be the height of the control 
var height = NSLayoutConstraint(item: movieView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: heightValue) 
//This will leave a marging of 10 at the end 
var trailing = NSLayoutConstraint(item: movieView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: videoViewBox, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10) 
//This will leave a marging of 10 at the start 
var leading = NSLayoutConstraint(item: movieView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: videoViewBox, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 10) 

movieView.setTranslatesAutoresizingMaskIntoConstraints(false) 

NSLayoutConstraint.activateConstraints([top, height, trailing, leading]) 
    videoViewBox.addSubview(movieView) 

moviePlayer.fullscreen = true 
moviePlayer.controlStyle = MPMovieControlStyle.None 
Смежные вопросы