天天看點

uikit——UIView——bounds frame

coordinate system

// animatable. do not use frame if view is transformed since it will not correctly reflect the actual location of the view. use bounds + center instead.
@property(nonatomic) CGRect            frame;

// use bounds/center and not frame if non-identity transform. if bounds dimension is odd, center may be have fractional part
@property(nonatomic) CGRect            bounds;      // default bounds is zero origin, frame size. animatable
@property(nonatomic) CGPoint           center;      // center is center of frame. animatable
@property(nonatomic) CGAffineTransform transform;   // default is CGAffineTransformIdentity. animatable
           

解釋:

  • frame:參考父view坐标系
  • bounds:參考view自身坐标系
  • center:參考父view坐标系

注1:view尺寸與坐标系無關,即frame.size和bound.size恒一緻 注2:獨立改變frame.size不改變center,frame.size改變以center為中心四周均勻變化

應用

- (void)showView
{
    self.view.backgroundColor = [UIColor purpleColor];
    
    {
        UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(60, 30, 200, 160)];
        UIView *sub = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
        
        parent.backgroundColor = [UIColor blueColor];
        sub.backgroundColor = [UIColor brownColor];
        
        [self.view addSubview:parent];
        [parent addSubview:sub];
    }
    
    {
        UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(60, 210, 200, 160)];
        UIView *sub = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
        
        parent.backgroundColor = [UIColor blueColor];
        sub.backgroundColor = [UIColor brownColor];
        
        [self.view addSubview:parent];
        [parent addSubview:sub];
        
        CGRect bounds = parent.bounds;
        bounds.origin = CGPointMake(20, 20);
        parent.bounds = bounds;
    }
    
    {
        UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(60, 390, 200, 160)];
        UIView *sub = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];
        
        parent.backgroundColor = [UIColor blueColor];
        sub.backgroundColor = [UIColor brownColor];
        
        [self.view addSubview:parent];
        [parent addSubview:sub];
        
        CGRect bounds = parent.bounds;
        bounds.origin = CGPointMake(-20, -20);
        parent.bounds = bounds;
    }
}
           
uikit——UIView——bounds frame

總結:

  • 子view左上角pos相對于父view左上角pos的offset為子view.frame.origin減去父view.bounds.origin,即子view在父坐标系中pos減去父view在自身坐标系中pos

注:bounds.origin改變本質是改變view自身坐标系原點(子view參考坐标系),是以會影響子view顯示

繼續閱讀