1 //建立View 2 let view1 =UIView() 3 let view2 =UIView(frame: CGRectMake(20,120, 100,100)) 4 let view3 =UIView(frame: CGRectMake(40,140, 100,100)) 5 6 //設置view的尺寸 7 view1.frame =CGRectMake(0,100, 100,100) 8 9 //設置view的背景色 10 view1.backgroundColor =UIColor.redColor() 11 view2.backgroundColor =UIColor.greenColor() 12 view3.backgroundColor = UIColor.blueColor() 13 14 //設置view的中心位置,不改變view的大小 15 view1.center =CGPointMake(80,200) 16 17 //改變view的寬和高,視圖原來的中心位置不變 18 view1.bounds =CGRectMake(0,0, 40,40); 19 20 //設置view的tag值 21 view1.tag =1; 22 view2.tag =2; 23 view3.tag =3; 24 25 //依次添加三個視圖(從上到下是:藍,綠,紅) 26 self.view.addSubview(view1) 27 self.view.addSubview(view2) 28 self.view.addSubview(view3) 29 30 //把view1(紅)移到最上面 31 self.view.bringSubviewToFront(view1) 32 33 //把view3(藍)移到最下面 34 self.view.sendSubviewToBack(view3) 35 36 //交換兩個視圖的位置 37 self.view.exchangeSubviewAtIndex(0, withSubviewAtIndex: 2) 38 39 //把一個視圖插在某個位置 40 self.view.insertSubview(view1, atIndex:2) 41 42 //把一個視圖插在另外一個視圖的下面 43 self.view.insertSubview(view1, belowSubview: view3) 44 45 //把一個視圖插在另外一個視圖的上面 46 self.view.insertSubview(view1, aboveSubview: view2) 47 48 //已經添加了某個視圖 49 self.view.didAddSubview(view1) 50 51 //將要移除某個視圖 52 self.view.willRemoveSubview(view1) 53 54 //把一個視圖從一個父視圖上移到另外一個父視圖上 55 self.view.willMoveToSuperview(view3) 56 57 //已經移動到了父視圖上 58 self.view.didMoveToSuperview() 59 60 //把一個視圖移動到一個窗口上 61 self.view.willMoveToWindow(UIApplication.sharedApplication().keyWindow) 62 63 //已經移動到了一個窗口上 64 self.view.didMoveToWindow() 65 66 //subViews中存放的(紅,綠,藍三個視圖) 67 let subViews :NSArray = NSArray.init(array:self.view.subviews) 68 69 //如何找到一個視圖,其實此時view4就是view1,view5也是view1 70 let view4 = subViews.objectAtIndex(0)as! UIView 71 view4.backgroundColor =UIColor.blackColor() 72 let view5 =self.view.viewWithTag(1) 73 view5?.backgroundColor =UIColor.purpleColor() 74 75 //隱藏view1 76 view1.hidden =true; 77 78 //刪除View2 79 view2.removeFromSuperview() 80 81 //再添加一個視圖 82 let lastView =UIView() 83 lastView.frame =CGRectMake(0,200, 200,200); 84 lastView.backgroundColor =UIColor.init(white:0.80, alpha: 1) 85 self.view.addSubview(lastView) 86 87 //設置view的透明度 88 lastView.alpha =0.5 89 90 //設置lastView的圓角角度 91 lastView.layer.cornerRadius =10 92 //設置邊框的的寬度 93 lastView.layer.borderWidth =2 94 //設置邊框的顏色 95 lastView.layer.borderColor =UIColor.redColor().CGColor 96 //容許剪切 97 lastView.clipsToBounds =true