在开发的时候,给控件和界面布局的一直使用CGRectMake,关于CGRect其他的方法比较少用,今天认真的去看了一下CGRect的其他方法,才发现还有很多方法对纯代码布局是很有用的。特别是下面这个几个,对于方法的作用,在代码块中又注释。
CGRectGetMinX,CGRectGetMaxX,CGRectGetMinY,CGRectGetMaxY,CGRectGetMidX,CGRectGetMidY
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
UIView*view = [[UIViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
view.backgroundColor = [UIColorgreenColor];
[self.view addSubview:view];
//获取view的最小X值,也就是这个view的X值
CGFloatminX =CGRectGetMinX(view.frame);NSLog(@"minx is %f",minX);
//获取view的最大的X值,也就是这个view的X值+view的宽
CGFloatmaxX =CGRectGetMaxX(view.frame);NSLog(@"maxX is %f",maxX);
//获取view的最小Y值,也就是这个view的Y值
CGFloatminY =CGRectGetMinY(view.frame);NSLog(@"minY is %f",minY);
//获取view的最大Y值,也就是这个view的Y值+view的高度
CGFloatmaxY =CGRectGetMaxY(view.frame);NSLog(@"maxY is %f",maxY);
//获取view的中点X
CGFloatmidX =CGRectGetMidX(view.frame);NSLog(@"midX is %f",midX);
//获取view的中点Y
CGFloatmidY =CGRectGetMidY(view.frame);NSLog(@"midY is %f",midY);
//获取view的高
CGFloatgetWidth =CGRectGetWidth(view.frame);NSLog(@"getWidth is %f",getWidth);
//获取view的宽
CGFloatgetHeight =CGRectGetHeight(view.frame);NSLog(@"getHeight is %f",getHeight);
//判断两个view大小是否一样
BOOLflag =CGRectEqualToRect(view.frame,self.view.frame);NSLog(@"flag is %d",flag);
//CGRectrect =CGRectStandardize(view.frame);
NSLog(@"rect x = %f, y = %f, width = %f, height = %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
//判断view的rect是否为空
BOOLflag1 =CGRectIsNull(view.frame);NSLog(@"flag is %d",flag1);
//断view的rect是否为空
BOOLflag2 =CGRectIsEmpty(view.frame);NSLog(@"flag2 is %d",flag2);
//基于某个view,传入X和Y,获取一个新的rect。
//官方文档给出的解释是另个view是否相交
CGRectsmallRect =CGRectInset(view.frame,-10,10);
NSLog(@"%f,%f,%f,%f",smallRect.origin.x,smallRect.origin.y,smallRect.size.width,smallRect.size.height);
UIView*view1 = [[UIViewalloc]initWithFrame:smallRect];
view1.backgroundColor = [UIColorredColor]; [self.view addSubview:view1];
}
网友评论