autoResizingMask 是UIView的一个属性,在一些简单的布局中,使用autoResizingMask,可以实现子控件相对于父控件的自动布局。
autoResizingMask 是UIViewAutoresizing 类型的,其定义为:
@property(nonatomic) UIViewAutoresizing autoresizingMask; // simple resize. default is UIViewAutoresizingNone
UIViewAutoresizing 是一个枚举类型,默认是 UIViewAutoresizingNone,其可以取得值有:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) { UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5 };
各属性解释:
UIViewAutoresizingNone |
不会随父视图的改变而改变 |
UIViewAutoresizingFlexibleLeftMargin |
自动调整view与父视图左边距,以保证右边距不变 |
UIViewAutoresizingFlexibleWidth |
自动调整view的宽度,保证左边距和右边距不变 |
UIViewAutoresizingFlexibleRightMargin |
自动调整view与父视图右边距,以保证左边距不变 |
UIViewAutoresizingFlexibleTopMargin |
自动调整view与父视图上边距,以保证下边距不变 |
UIViewAutoresizingFlexibleHeight |
自动调整view的高度,以保证上边距和下边距不变 |
UIViewAutoresizingFlexibleBottomMargin |
自动调整view与父视图的下边距,以保证上边距不变 |
注意:autoResizingMask 既可以在代码中直接使用,也可以在UIStoryboard中使用。
一个代码中使用autoResizingMask的例子:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; UIViewController *viewController = [[UIViewController alloc] init]; self.window.rootViewController = viewController; self.window.backgroundColor = [UIColor whiteColor]; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20,100,200,100)]; [view setBackgroundColor:[UIColor grayColor]]; [self.window addSubview:view]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20,20,50,50)]; [button setBackgroundColor:[UIColor whiteColor]]; [view addSubview:button]; //距离父视图右边距不变 //button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; //距离父视图的左边距不变 //button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; //距离父视图的左右边距不变,button大小会调整 //button.autoresizingMask = UIViewAutoresizingFlexibleWidth; //view.frame = CGRectMake(20,100,300,100); //距离父视图的下边距不变 //button.autoresizingMask = UIViewAutoresizingFlexibleTopMargin; //距离父视图的上边距不变 //button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin; //距离父视图的上下边距不变,button大小会调整 button.autoresizingMask = UIViewAutoresizingFlexibleHeight; view.frame = CGRectMake(20,100,200,200); [self.window makeKeyAndVisible]; return YES; }
另外,autoResizingMask 可以组合使用。例如:
button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin;
表示的是,子控件相对于父控件的顶部和右侧的距离不变。
时间: 2024-11-05 12:25:57