1. 程式人生 > >UIView 子view跟隨父view動態變化

UIView 子view跟隨父view動態變化

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    
    UIView *view1 = [[UIView alloc]init];
    view1.frame = CGRectMake(100, 100, 100, 100);
    view1.backgroundColor = [UIColor blackColor];
    //允許子檢視自適應
    view1.tag = 100;
    view1.autoresizesSubviews = YES;
    [self.view addSubview:view1];
    
    UIView *view2 = [[UIView alloc]init];
    view2.frame = CGRectMake(25, 25, 50, 50);
    view2.backgroundColor = [UIColor whiteColor];
    //設定子檢視適應方式
    view2.autoresizingMask =
    UIViewAutoresizingFlexibleLeftMargin   |
    UIViewAutoresizingFlexibleWidth        |
    UIViewAutoresizingFlexibleRightMargin  |
    UIViewAutoresizingFlexibleTopMargin    |
    UIViewAutoresizingFlexibleHeight       |
    UIViewAutoresizingFlexibleBottomMargin ;
    [view1 addSubview:view2];
    
    UIButton *btn = [[UIButton alloc]init];
    btn.frame = CGRectMake(0, frame.size.height-200, 50, 50);
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"變化" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

-(void)click:(UIButton *)btn{
   UIView *view1 =  [self.view viewWithTag:100];
    CGRect frame = view1.frame;
    view1.frame = CGRectMake(frame.origin.x-20, frame.origin.y-20, frame.size.width+40, frame.size.height+40);
}


UIView的檢視自適應

父級view1中,包含一個view2,view1的大小變化時,view2可以根據設定條件,與view1一同變化:

view1先設定屬性 ,使子view可以動態改變大小:

view1.autoresizesSubviews =YES;

view2子控制元件設定autoresizeingMask屬性,來決定父view變化,子view做出怎樣相應的變化:

    view2.autoresizingMask =

UIViewAutoresizingFlexibleLeftMargin   |

UIViewAutoresizingFlexibleWidth

        |

UIViewAutoresizingFlexibleRightMargin  |

UIViewAutoresizingFlexibleTopMargin    |

UIViewAutoresizingFlexibleHeight       |

UIViewAutoresizingFlexibleBottomMargin ;