masonry设置约束后如何获取正确的frame

纯代码实现自定义布局,我通常使用masonry和设置frame同时进行,然而masonry设置约束后并不能直接反应到frame上.

约束转frame需要时间,设置约束后直接使用frame全部为(0,0,0,0).比如:

- (void)setTableView {

UITableView *tableView = [[UITableView alloc] init];

tableView.frame = CGRectMake(0, CGRectGetMaxY(self.midView.frame), WSWIDTH, WSHEIGHT - CGRectGetMaxY(self.midView.frame) - 150 - 49 );

tableView.tableFooterView = [[UIView alloc] init];

tableView.delegate = self;

tableView.dataSource = self;

self.tableView = tableView;

[tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WSSizeNumCell class]) bundle:nil] forCellReuseIdentifier:joinGoodsTrainsId];

[self.contentV addSubview:tableView];

}

这里想利用之前用masonry约束好的midView的frame设置tableView的位置,但是这里self.midView.frame仍然为(0,0,0,0)

要想获取到正确的frame,要利用到layoutIfNeeded

layoutIfNeeded:告知页面需要立即更新,如果希望立即生成新的frame需要调用此方法.

如下:

- (void)setTableView {

[self.view layoutIfNeeded];

UITableView *tableView = [[UITableView alloc] init];

tableView.frame = CGRectMake(0, CGRectGetMaxY(self.midView.frame), WSWIDTH, WSHEIGHT - CGRectGetMaxY(self.midView.frame) - 150 - 49 );

tableView.tableFooterView = [[UIView alloc] init];

tableView.delegate = self;

tableView.dataSource = self;

self.tableView = tableView;

[tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WSSizeNumCell class]) bundle:nil] forCellReuseIdentifier:joinGoodsTrainsId];

[self.contentV addSubview:tableView];

}

这个时候获取的frame就是正确的.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容