无夜之星辰
无夜之星辰

Reputation: 6178

Why I can't get the frame immediately when I use masonry?

This code:

[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
}];
NSLog(@"%@", self.scrollView);

result is:<UIScrollView: 0x7faad400cc00; frame = (0 0; 0 0)

However this code:

[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    NSLog(@"%@", self.scrollView);
});

result is:<UIScrollView: 0x7ff8d1043200; frame = (0 0; 375 667);

Why I can't get the frame immediately but I can get after 0.1 second?

Upvotes: 0

Views: 549

Answers (2)

Glenn Posadas
Glenn Posadas

Reputation: 13290

Simply because you are changing your view's constraints/layout in a block. If you understand what a block does completely, you will know the answer to your question.

The program will run from the first line of your code, and go through the NSLog method line, and the codes inside the block will either be called first before the NSLog line ,Or after the NSLog line. As what you've said, you can get the frame after 0.1 second. Again that's because the codes inside the block finishes slower than the NSLog line.

Upvotes: 0

Bimawa
Bimawa

Reputation: 3720

Masonry is a wrapper for autolayouts, and autolayouts calculate itself frame in - (void)layoutSubviews; method, and only after that u can get frames of all views.

masonry methods mas_makeConstraints and similar just setups Constraints no more.

And if you need update constraints you must call mas_remakeConstraints: its just update constraits, for update Frames of views, we must call method setNeedsLayout for setup a flag about recalculation in next Display cycle, and if we want update frames immediately we must call layoutIfNeeded method.

Upvotes: 2

Related Questions