1. 程式人生 > >iOS之UIView檢視的基本操作(Swift4.2)

iOS之UIView檢視的基本操作(Swift4.2)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
   
 //        UIView檢視的基本操作

        let rect = CGRect(x: 30, y: 50, width: 200, height: 200)
        let view = UIView(frame: rect)
        view.backgroundColor = UIColor.brown
        self.view.addSubview(view)

        let btAdd = UIButton(frame: CGRect(x: 30, y: 350, width: 80, height: 30))
        btAdd.backgroundColor = UIColor.gray
        btAdd.setTitle("Add", for: UIControl.State())
        btAdd.addTarget(self, action: #selector(ViewController.addView(_ :)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btAdd)

        let btBack = UIButton(frame: CGRect(x: 120, y: 350, width: 80, height: 30))
        btBack.backgroundColor = UIColor.gray
        btBack.setTitle("Switch", for: UIControl.State())
        btBack.addTarget(self, action: #selector(ViewController.bringViewBack(_ :)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btBack)

        let btRemove = UIButton(frame: CGRect(x: 210, y: 350, width: 80, height: 30))
        btRemove.backgroundColor = UIColor.gray
        btRemove.setTitle("Remove", for: UIControl.State())
        btRemove.addTarget(self, action: #selector(ViewController.removeView(_ :)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btRemove)
}


       @objc func addView(_ sender:UIButton!)
        {
            let rect = CGRect(x: 60, y: 90, width: 200, height: 200)
            let view = UIView(frame: rect)
            view.backgroundColor = UIColor.purple
            view.tag = 1;

            self.view.addSubview(view)

        }

      @objc  func bringViewBack(_ sender:UIButton!)
        {
            let view = self.view.viewWithTag(1)
            self.view.sendSubviewToBack(view!)

        }

    @objc func removeView(_ sender: UIButton!)
        {
            let view = self.view.viewWithTag(1)
            view?.removeFromSuperview()
        }
}

通過設定三個按鈕給一個view新增另一個view,並可以進行兩個view之間的切換,以及移除一個view。

程式執行時:

 按下Add按鈕後:

按下Switch按鈕進行切換:

  

 進行Remove操作: