美文网首页
iOS 设置UIView的圆角

iOS 设置UIView的圆角

作者: 大荣纸 | 来源:发表于2017-03-16 11:47 被阅读803次

介绍两种方法:

1、首先简单的说下UIView的CALayer.

UIView之所以能显示在屏幕上,完全是因为它内部的一个图层,在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层

@property(nonatomic,readonly,retain) CALayer *layer;

当UIView需要显示到屏幕上时,会调用drawRect:方法进行绘图,并且会将所有内容绘制在自己的图层上,绘图完毕后,系统会将图层拷贝到屏幕上,于是就完成了UIView的显示。因此,通过操作这个CALayer对象,可以很方便地调整UIView的一些界面属性,比如:阴影、圆角大小、边框宽度和颜色等。

总结:UIView本身不具备显示的功能,拥有显示功能的是它内部的图层。

对一个UIView设置它的圆角

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

view.backgroundColor = [UIColor redColor];

view.layer.cornerRadius = 25;

[self.view addSubview:view];

但是当我们往view上面添加一个UILabel或者一个UIButton时,如下代码就不能显示圆角效果:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];

label.text = @"93";

label.textAlignment = NSTextAlignmentCenter;

label.backgroundColor =[UIColor redColor] ;

label.layer.cornerRadius = 15;

[view addSubview:label];

我们需要添加masksToBounds才可以实现圆角效果:

label.layer.masksToBounds = YES;

借鉴自:文大大CALayer简介

2、在xib文件中实现圆角

假如需要设置一个UIImageView的圆角,打开xib文件,选中需要设置的imageView,点击Xcode右边第三个属性设置,找到User Defined Runtime Attributes,点击下面的加号,双击keyPath,粘贴layer.cornerRadius,修改后面的值,再次点击加号,粘贴layer.masksToBounds,修改为YSE,OK,完成了

相关文章

网友评论

      本文标题:iOS 设置UIView的圆角

      本文链接:https://www.haomeiwen.com/subject/ovndnttx.html