I need to show some people what it was like before Autolayout, so I wanted to try autoresizing masks to build a view that looks like this:
————————————
| ———————— |
| | red | |
| | | |
| ———————— |
| |
| yellow |
————————————
I want the red UIView to expand horizontally but to keep its left, top, and right margins at 20 points when the device is rotated.
Here's my code:
// .h
@interface NextViewController : UIViewController
@end
// .m
@interface NextViewController ()
@property (nonatomic) UIView *rectView;
@end
@implementation NextViewController
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:CGRectZero];
self.view.backgroundColor = [UIColor yellowColor];
// 280 width for iPhone 5S when left and right paddings are 20 points
self.rectView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 100)];
[self.view addSubview:self.rectView];
self.rectView.backgroundColor = [UIColor redColor];
self.rectView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
}
@end
My problem is that the red UIView always goes beyond the yellow UIView's width:
I printed the red view's description:
Printing description of $15:
<UIView: 0x7fc360e181c0; frame = (20 20; 600 100); autoresize = W; layer = <CALayer: 0x600000226960>>
So what am I doing wrong?
Ah, I get it now. It's this line:
self.view = [[UIView alloc] initWithFrame:CGRectZero];
The subviews' autoresizing masks are being evaluated against this CGRectZero
frame of the top-level view which is why they aren't being resized correctly. I gave it the frame of an iPhone 5S screen on portrait mode instead, and that fixed the rotation scaling:
self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.