先描述问题
问题是这样的,我给一个蓝色的view上加一个黑色的view,然后黑色的view的center.x是蓝色的width的四分之一,结果蓝色的view的width是414,将他的四分之一赋值给黑色的center.x的时候,结果出现了偏差,按道理414/4.0应该是103.5,但是赋值给center.x的时候就自动变成了175.95
问题代码及测试Log
UIImageView *dataLumpView= [[UIImageView alloc]init];
dataLumpView.backgroundColor = [UIColor blackColor];
[self addSubview:dataLumpView];
/******************问题就在下面*********************/
[dataLumpView setCenter:CGPointMake(self.bounds.size.width/4.0, self.bounds.size.height*1/10.0)];
[dataLumpView setWidth:0.35*self.bounds.size.width];
[dataLumpView setHeight:0.32*self.bounds.size.height];
/******************End*******************************/
NSLog(@"背景蓝色view的宽度除以4是%f",self.bounds.size.width/4.0);
NSLog(@"黑色view的centerX是%f***************************",dataLumpView.center.x);
输出
背景蓝色view的宽度除以4是103.500000
黑色view的centerX是103.500000
解决办法
调换设置center的语句和设置width/height的语句
以后记住要先设置控件宽高,后设置center相关属性
正确代码
UIImageView *dataLumpView= [[UIImageView alloc]init];
dataLumpView.backgroundColor = [UIColor blackColor];
[self addSubview:dataLumpView];
[dataLumpView setWidth:0.35*self.bounds.size.width];
[dataLumpView setHeight:0.32*self.bounds.size.height];
[dataLumpView setCenter:CGPointMake(self.bounds.size.width/4.0, self.bounds.size.height*1/10.0)];
// }
NSLog(@“背景蓝色view的宽度除以4是%f”,self.bounds.size.width/4.0);
NSLog(@“黑色view的centerX是%f***************************”,dataLumpView.center.x);