iOS Constraints on Grid of Equal Width/Height Buttons cause positioning and size to vary

杀马特。学长 韩版系。学妹 提交于 2019-12-07 10:32:28

Ok, I figured out how to make it work with only constraints. There were just too many interconnected dependencies and the system couldn't handle it. I was selecting the entire grid of buttons and adding Equal Heights and Equal Widths constraints to all of them, which meant each button was dependent upon every other button.

Instead, I did it row by row. I selected one row:

I applied the Equal Heights and Equal Widths constraints to each item in that row. Then I did the same to Row 2, then Row 3, etc. So, each row was depending only on itself. However, those constraints weren't enough to define the UI completely, because the Height was still undefined.

So, then I selected the first column (i.e. first item in each row) and applied Equal Widths and Equal Heights constraints to those items. Then all of the constraints behaved properly and I didn't receive any Misplaced Views warnings.

I believe this worked because the constraints on the columns could resolve the Height of each row and then row could resolve it's own Widths without having to interact with any other row.

The small amount of code below (and setting the cell size and minimum spacings in the storyboard) will give you your keyboard using a collection view.

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@end

@implementation ViewController

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 40;
}

-(UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = (indexPath.row % 2 == 0)? [UIColor colorWithRed:180/255.0 green:210/255.0 blue:254/255.0 alpha:1] : [UIColor colorWithRed:50/255.0 green:167/255.0 blue:85/255.0 alpha:1];
    return cell;
}

This gives the following result,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!