1.UIWindow(在AppDelegate.swift中設(shè)置其屬性)
-
command+c創(chuàng)建MyViewController.swift文件之拨。自定義ViewController
class MyViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //設(shè)置它的背景顏色 self.view.backgroundColor=#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1) }
-
將MyViewController的對(duì)象設(shè)置為window的根視圖控制器丁侄,把window設(shè)置成系統(tǒng)的window
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //初始化window self.window = UIWindow(frame: UIScreen.main.bounds) //初始化控制器 let myVC = MyViewController() //設(shè)置成window的根視圖控制器 self.window?.rootViewController=myVC //把window設(shè)置成系統(tǒng)的window self.window?.makeKeyAndVisible() return true }
2.UIView
//將view的視圖大小存放在rect中
let rect = CGRect(x: 30, y: 30, width: 100, height: 200)
//初始化view并設(shè)置其大小
let subView : UIView = UIView(frame: rect)
//獲取當(dāng)前控制器的view,設(shè)置背景顏色為紅色
subView.backgroundColor=UIColor.red
//添加到父視圖
self.view.addSubview(subView)
let subView1 = UIView()
subView1.frame = CGRect(x: 140, y: 240, width: 100, height: 100)
//設(shè)置subView1的背景顏色
subView1.backgroundColor=UIColor.yellow
self.view.addSubview(subView1)
let subView2 = UIView()
subView2.frame = CGRect(x: 10, y: 10, width: 50, height: 50)
subView2.backgroundColor=UIColor.green
//subView2添加到subView1上
subView1.addSubview(subView2)
//將subView2添加到subView上
subView.addSubview(subView2)
//frame 相對(duì)于父視圖的
//bounds 相對(duì)于自身坐標(biāo)
print(subView2.bounds)
//center
let subView3=UIView()
self.view.addSubview(subView3)
subView3.frame=CGRect(origin: self.view.center, size: CGSize(width: 100, height: 100))
subView3.backgroundColor=#colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1)
//透明度
//subView3.alpha = 0.1 //這個(gè)屬性會(huì)影響到放在它上的視圖的屬性
subView3.backgroundColor=UIColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)//
let subView4 = UIView(frame: CGRect(x: 10, y: 10, width: 40, height: 40))
subView4.backgroundColor=#colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
subView3.addSubview(subView4)
//subView4.isHidden=true//隱藏
//tag 使用2000以上
subView4.tag = 10001
let tagView = subView3.viewWithTag(10001)
print("subView4 = \(subView4),TagView = \(tagView)")
//用戶交互
//self.view.isUserInteractionEnabled = false
//superView
print("superView = \(subView4.superview),subView3 = \(subView3)")
//子視圖
for item in self.view.subviews {
//從父視圖上移除
item.removeFromSuperview()
}
}
override func touchesBegan(_ touches:Set<UITouch>, with event :UIEvent?){
print("點(diǎn)擊了當(dāng)前控制器")
}
```