用纯自动布局如何判断子控件超出了父控件?

如图:

clipboard.png

标签从左到右依次排列,如果超出了父view,则自动换行。
如果使用的frame,只需判断标签的maxX是否大于父view的宽度即可。
但如果使用masonry,如何判断当前创建的标签超出了父view?

待补全的代码:

UILabel *lastLabel = nil;

for (int i = 0; i < arr.count; i ++) {
    UILabel *label = [[UILabel alloc] init];
    [bgView addSubview:label];
    label.text = arr[i];
    if (lastLabel == nil) {
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.height.mas_equalTo(14);
            make.top.mas_offset(2);
        }];
    } else {
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(lastLabel.mas_right).mas_offset(20);
            make.height.top.mas_equalTo(lastLabel);
        }];
    }
    
    // 如果label超出父视图右边距,换行
    if (这里怎么写?) {
        [label mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.top.mas_equalTo(lastLabel.mas_bottom).mas_offset(5);
        }];
    }
    lastLabel = label;
}
阅读 5.5k
3 个回答

这个并不是用约束的最佳使用场景,计算frame感觉也不太好。
我觉得这个视图排列和视图其实并没有多大关系,因为并不是你设置了文字,视图就会有尺寸,而尺寸又和文字有关。所以,我认为你应该计算的是文字大小而非视图。
当然,如果你用collectionView 就不用计算了。

该情形应该使用 collectionView 而不是手动布局,即使你是需要在 Cell 里面进行布局也可以使用。你可以在自定义 Cell 里面添加 collectionView 作为子视图。你可以搜一下 IrregularGridCollectionView,该 UI 控件应该可以满足你的要求。

_categoryGrid = [IrregularGridCollectionView irregularGridCollectionViewWithFrame:CGRectMake(0, topView.bottom, YTScreenW, 200)
                            delegate:self
                       registerCells:@[gridViewCellClassType([SortMenuCategoryCell class],@"SortMenuCategoryCell")]
                     scrollDirection:UICollectionViewScrollDirectionVertical
                   contentEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10) 
                         lineSpacing:10.0 
                    interitemSpacing:10.0
                           gridHeight:30];
    
_categoryGrid.backgroundColor = [UIColor whiteColor];
_categoryGrid.tag      = 100;
_categoryGrid.adapters = array;
[_categoryGrid resetSize];

[self.contentView addSubview:_categoryGrid ];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题