UIView frame, bounds and center

后端 未结 6 855
梦谈多话
梦谈多话 2020-11-22 10:40

I would like to know how to use these properties in the right manner.

As I understand, frame can be used from the container of the view I am creating. I

6条回答
  •  没有蜡笔的小新
    2020-11-22 11:17

    After reading the above answers, here adding my interpretations.

    Suppose browsing online, web browser is your frame which decides where and how big to show webpage. Scroller of browser is your bounds.origin that decides which part of webpage will be shown. bounds.origin is hard to understand. The best way to learn is creating Single View Application, trying modify these parameters and see how subviews change.

    - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 200.0f, 200.0f, 400.0f)];
    [view1 setBackgroundColor:[UIColor redColor]];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];
    [view2 setBackgroundColor:[UIColor yellowColor]];
    [view1 addSubview:view2];
    
    [[self view] addSubview:view1];
    
    NSLog(@"Old view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
    NSLog(@"Old view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
    
    // Modify this part.
    CGRect bounds = view1.bounds;
    bounds.origin.x += 10.0f;
    bounds.origin.y += 10.0f;
    
    // incase you need width, height
    //bounds.size.height += 20.0f;
    //bounds.size.width += 20.0f;
    
    view1.bounds = bounds;
    
    NSLog(@"New view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
    NSLog(@"New view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
    

提交回复
热议问题