xcode增加视图交换图层并删除swift代码

本文通过一个SwiftUI应用实例介绍了如何在iOS应用中添加、移除和切换视图。文章展示了如何使用SwiftUI创建按钮,并通过这些按钮来控制视图的添加、移除及显示顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import UIKit

import Foundation

class ViewController: UIViewController {

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        

        

        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:UIControlState())

        btAdd.addTarget(self, action:#selector(ViewController.addView(_:)),for:UIControlEvents.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: UIControlState())

        btBack.addTarget(self, action:#selector(ViewController.bringViewBack(_:)),for:UIControlEvents.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: UIControlState())

        btRemove.addTarget(self, action:#selector(ViewController.removeView(_:)),for:UIControlEvents.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.sendSubview(toBack:view!)

    }

    @objc func removeView(_ sender:UIButton!)

    {let view = self.view.viewWithTag(1)

        view?.removeFromSuperview()}

    

        

        

    


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

        

    }

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值