ios开发之UIView类

UIView是UIKit框架中的视图类,是所有控件的父类

在xcode中通过如下方式定义一个UIview视图

let view = UIView(frame: CGRect(x: 40, y: 40, width:100, height: 100))//定义一个UIview视图
self.view.addSubview(view)//将UIview视图添加到视图控制器中

其中frame表示一个矩形,使用CGRect对象来对矩形的参数进行存储。(x, y)为矩形的坐标,左边的原点为左上角,x的正方形向右,y的正方向向下,width和height为矩形的宽度和高度。也可写作:

let viewFrame = CGRect(x: 40, y: 40, width:100, height: 100)
let view = UIView(frame: viewFrame)
self.view.addSubview(view)

通过backgroundColor定义控件的背景颜色
通过alpha属性来定义透明度
通过isHidden属性来定义隐藏属性

let view = UIView(frame: CGRect(x: 40, y: 40, width:100, height: 100)
view.backgroundColor = UIColor.blue //将UIView的背景定义为蓝色
view.alpha = 0.5 //空间的透明度在0~1之间,其中0表示完全透明,1表示完全不透明。不设置时默认值为1
				 //当透明度为0时,整个视图会被隐藏,且不可被响应
view.isHidden = true //当ishidden属性为true时,相当于alpha属性为0
self.view.addSubview(view)

通过clipsToBounds属性来定义视图是否会对其子视图的边界进行裁切,当父视图的clipsToBounds属性为false时,子视图中超出其父视图的部分仍然会被显示。当clipsToBounds属性为true时,会对子视图中超出父视图边间的部分进行裁切,仅显示其父视图当中的部分。

let view = UIView(frame: CGRect(x: 40, y: 40, width:100, height: 100)
view.backgroundColor = UIColor.blue
view.clipsToBounds = true  //对超出view边界的部分进行裁切

let subView = UIView(frame: CGRect(x: 60, y: 60, width:100, height: 100)
view.backgroundColor = UIColor.yellow

view.addSubview(subView)
self.view.addSubview(view)

通过bounds属性来对view中的视图以及子视图的坐标原点进行改动

view.bounds = CGRect(x: ,y: ,width: ,height: )

其中(x,y)视图的origin相对于子视图的坐标。width和height为视图的缩放尺寸,视图以center坐标为中心进行缩放,缩放后会修改origin坐标。

可以通过insertSubview属性来对同一级别的视图先后顺序进行修改,在默认情况下,如:

let view1 = UIView(frame: CGRect(x: 40, y: 40, width:100, height: 100)
view1.backgroundColor = UIColor.black

let view2 = UIView(frame: CGRect(x: 60, y: 60, width:100, height: 100)
view2.backgroundColor = UIColor.green

let view3 = UIView(frame: CGRect(x: 80, y: 80, width:100, height: 100)
view1.backgroundColor = UIColor.yellow

self.view.addSubview(view1)
self.view.addSubview(view2)
self.view.addSubview(view3)

视图中重叠部分从上至下依次为view3,view2,view1。但如果在下面添加

self.view.insertSubview(view3, belowSubview: view1)

则视图中重叠部分从上至下依次为view2,view1,view3。
insertSubview属性有三种,分别为:

self.view.insertSubview(view:UIView, belowSubview: UIView)
self.view.insertSubview(view:UIView, at: Int) //在指定的位置插入视图
self.view.insertSubview(view:UIView, aboveSubview: UIView)

bringSubviewToFront属性可以将某个视图移到同级别视图的最前面

self.view.bringSubviewToFront(view: UIView)

removeFromSuperview可以将子视图从父视图中移除

view1.removeFromSuperview()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值