Ios 视图和superview之间的自动布局标准空间不工作
我正在使用使子视图的框架与其superview的框架相匹配,减去标准空间量(约8px)(“标准空间”在视觉格式语言中表示为Ios 视图和superview之间的自动布局标准空间不工作,ios,uikit,autolayout,Ios,Uikit,Autolayout,我正在使用使子视图的框架与其superview的框架相匹配,减去标准空间量(约8px)(“标准空间”在视觉格式语言中表示为-) 这是我的密码: class ViewController: UIViewController { var imageView: UIImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() self.view.backgro
-
)
这是我的密码:
class ViewController: UIViewController {
var imageView: UIImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.redColor()
imageView.backgroundColor = UIColor.greenColor()
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(imageView)
let viewsDict = ["imageView": imageView]
let imageViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-|",
options: NSLayoutFormatOptions.allZeros,
metrics: nil,
views: viewsDict)
self.view.addConstraints(imageViewConstraintsH)
let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[imageView]-|",
options: NSLayoutFormatOptions.allZeros,
metrics: nil,
views: viewsDict)
self.view.addConstraints(constraintsV)
}
}
正如您在下面的屏幕截图中所看到的,标准间距是水平的,而不是垂直的:
我无法回答为什么它不起作用(Apple DTS也不能),但您可以使用superview中的内置布局指南来完成相同的任务,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
id topLayoutGuide = self.topLayoutGuide;
id bottomLayoutGuide = self.bottomLayoutGuide;
UIImageView *imageView = [[UIImageView alloc]init];
[imageView setTranslatesAutoresizingMaskIntoConstraints:false];
NSDictionary *views = NSDictionaryOfVariableBindings(imageView, topLayoutGuide, bottomLayoutGuide);
self.view.backgroundColor = [UIColor grayColor];
imageView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:imageView];
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[imageView]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(imageView)]
];
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topLayoutGuide]-[imageView]-[bottomLayoutGuide]"
options:0
metrics:nil
views:views]
];
}
多亏了T·库珀