Eric
Eric

Reputation: 16921

Auto Layout standard space between view and superview not working

I'm using the Auto Layout Visual Format Lanugage to make a subview's frame fit its superview's frame, minus the standard amount of space (approx. 8px) (a "standard space" is represented as a - in visual format language).

Here's my code:

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

As you can see in the screenshot below, the standard spacing is respected horizontally, but not vertically:

enter image description here

Upvotes: 1

Views: 141

Answers (1)

Foster Bass
Foster Bass

Reputation: 908

I can't answer WHY it isn't working (neither could Apple DTS), but you can use the built-in layout guides from the superview to accomplish the same thing, like this:

- (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]
     ];

}

Thanks to T. Cooper

Upvotes: 1

Related Questions