我遇到了与Auto Layout遇到的问题。
我有一个UIView
设置了约束,因此它对于每个尺寸类都处于相同的位置。我想让我的视频完全适合这个UIView
videoViewBox
。我只在iPhone 6上工作,但是如果我切换到iPhone 4S / 5,视频就不再对齐了。
这是代码:
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
的值,但它也没有对齐。
我该怎么做呢?谢谢你的帮助!
答案 0 :(得分:6)
不要为moviePlayer视图设置框架。相反,添加Autolayout约束以将moviePlayer视图约束到其超级视图。您可以使用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)
或者,您可以使用锚点:
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
答案 1 :(得分:0)
You need to use AutoLayoutConstrains to achieve this.
You can both, apply such constrains directly over your storyboard or by code. I'm assuming that what you want is to do it by code. In that case this should be the way to go:
name_buff