iOS之UIView视图的基本操作(Swift4.2)

版权声明:Created by 影子传说 // Copyright © 2018年 影子传说. All rights reserved. https://blog.csdn.net/jaydneg23333/article/details/82824211
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操作:

猜你喜欢

转载自blog.csdn.net/jaydneg23333/article/details/82824211
今日推荐