自动布局 - 如何添加子视图以匹配UIView的大小?

Jor*_*dan 3 ios autolayout swift

我遇到了一个与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
    }
Run Code Online (Sandbox Code Playgroud)

我尝试设置的值CGRect与值动态videoViewBox.frame.origin.xvideoViewBox.frame.origin.y,但它也不对齐.

我该怎么做呢?谢谢你的帮助!

vac*_*ama 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)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用锚点:

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
Run Code Online (Sandbox Code Playgroud)