视图的基本操作
视图的层次关系
//初始化一个CGRect对象,定义一个矩形显示区域
让view1 = UIView(frame:CGRect(x:20,y:80,width:280,height:280))
view1.backgroundColor = UIColor.red
self.view.addSubview(厂景)
let view2 = UIView(frame:CGRect(x:0,y:0,width:200,height:200))
//设置查看坐标系统的位置和大小
view2.bounds = CGRect(x:-40,y:-20,width:200,height:200)
view2.backgroundColor = UIColor.yellow
self.view.addSubview(视图2)
//添加第三个视图到视图2
let viewsub = UIView(frame:CGRect(x:0,y:0,width:100,height:100))
viewsub.backgroundColor = UIColor.blue
view2.addSubview(viewsub)
实战:
让view = UIView(frame:CGRect(x:30,y:50,width:200,height:200))
view.backgroundColor = UIColor.brown
self.view.addSubview(视图)
let btAdd = UIButton(frame:CGRect(x:30,y:350,width:80,height:30))
btAdd.backgroundColor = UIColor.gray
btAdd.setTitle(“Add”,for:UIControlState())
btAdd.addTarget(self,action:#selector(ViewController.addView(_ :)),用于:UIControlEvents.touchUpInside)
self.view.addSubview(btAdd)
让btBack = UIButton(框架:CGRect(x:120,y:350,宽度:80,高度:30))
btBack.backgroundColor = UIColor.gray
btBack.setTitle(“Switch”,for:UIControlState())
btBack.addTarget(self,action:#selector(ViewController.bringViewback(_ :)),用于:UIControlEvents.touchUpInside)
self.view.addSubview(btBack)
让btRemove = UIButton(框架:CGRect(x:210,y:350,宽度:80,高度:30))
btRemove.backgroundColor = UIColor.gray
btRemove.setTitle(“Remove”,for:UIControlState())
btRemove.addTarget(self,action:#selector(ViewController.removeView(_ :)),用于:UIControlEvents.touchUpInside)
self.view.addSubview(btRemove)
}
@objc func addView(_ sender:UIButton)
{
let view = UIView(frame:CGRect(x:60,y:90,width:200,height:200))
view.backgroundColor = UIColor.purple
//设置id
view.tag = 1;
self.view.addSubview(视图)
}
@objc func bringViewback(_ sdender:UIButton)
{
//通过标志,找到新添加的视图
让view = self.view.viewWithTag(1)
//把它移到所有视图后面
self.view.sendSubview(toBack:view!)
}
@objc func removeView(_ sender:UIButton)
{
让view = self.view.viewWithTag(1)
//从当前视图控制器中删除
查看?.removeFromSuperview()
}