Kex
Kex

Reputation: 8609

Setting constraints in a UITableView cell, keeping UIButtons appropriately spaced

this is something I have a problem with. I have done a bunch of tutorials on constraints in the interface builder and I understand pinning. My app below uses a UITableView and in the UITableView cells there are 4 UIButtons and 4 UILabels. I want to keep the spacing even like below for larger screen sizes. I guess what I mean is I want the spacing to dynamically increase with the screen size but the size of the images remains the same. If I try pinning the left and right UIButtons to their respective edges of the container this distance will not dynamically increase and there will be a big gap in the centre. How can I set it up so the layout is the same that for the smaller screen size?

enter image description here

Upvotes: 0

Views: 253

Answers (1)

foundry
foundry

Reputation: 31745

You can add some transparent views to the superview, and use them as spacers. I thought this was weird at first, but I noticed that Apple recommends it (it even turns up as a suggestion in one of their amazingly informative NSLayout debug messages)

[self.view addConstraints:
 [NSLayoutConstraint constraintsWithVisualFormat:
                           @"H:|[spacer1][view1]\
                           [spacer2(==spacer1)][view2]\
                           [spacer3(==spacer1)][view3]\
                           [spacer4(==spacer1)][view4]\
                           [spacer5(==spacer1)]|"

                                         options:NSLayoutFormatAlignAllTop
                                         metrics:0
                                           views:viewsDictionary]];

The trick, as you see, is to set each spacer's width as equal to the first spacer. Then you will get even distribution of your visible views. In you case, you would add each of your button/image combos to a container view (view1 ... view4).

In the storyboard...

enter image description here

The blue views represent the (transparent) spacer views. This is the setting to get them to resizeable equal widths. You should also set the visible button/imageview combos to fixed widths.

Although this example says 'add two constraints' it actually adds four, all marked as 'equal width to view' - but it seems to do the right thing. You will also want to set the space between each view ('spacing to nearest neighbour') to zero.

Upvotes: 2

Related Questions