视图和超级视图之间的自动布局标准空间不起作用

时间:2015-03-26 19:15:41

标签: ios uikit autolayout

我使用Auto Layout Visual Format Lanugage使子视图的框架适合其超视图的框架,减去标准的空间量(约8px)(a"标准空间"用可视格式语言表示为-

这是我的代码:

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)
    }
}

正如您在下面的屏幕截图中看到的那样,标准间距是水平的,但不是垂直的:

enter image description here

1 个答案:

答案 0 :(得分:1)

我无法解答为什么它不起作用(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. Cooper