您无法在 Interface Builder 中实现您想要做的事情。但这可以通过通过代码创建约束来实现。我为您创建了一个示例项目,您可以从这里下载
下面是通过代码添加约束的 ViewController 文件的代码。注意:我在 Interface Builder 中添加了任意约束,因为我们需要获取主视图高度。这些也很重要
//
// ViewController.swift
// Test
//
// Created by FR-MAC on 11/12/14.
// Copyright (c) 2014 ABC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mySubview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.addContraintsForMoviePlayerView(self.mySubview, superView: self.view)
}
func addContraintsForMoviePlayerView(var view:UIView, superView:UIView) -> Void {
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let leftConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0)
let rightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)
var topValue:CGFloat = superView.frame.size.height
topValue = topValue/2
let topConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view.superview?, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: topValue)
// Remove the constraints created in Interface Builder to avoid autolayout constraint issues. We just added those constraints to get the correct height of self.view.frame which we used to create above topConstaint
self.view.removeConstraints(self.view.constraints())
//Add the above created constraints
superView.addConstraints( [leftConstraint, rightConstraint, topConstraint, bottomConstraint] )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
希望这可以帮助你:)