"闪闪"霓虹灯

作者: 寂婧_欢喜 | 来源:发表于2016-11-18 18:11 被阅读73次

    今天学习了有趣的霓虹灯效果的swift代码,现在来和大家分享

    先看一下闪闪的效果图,只弄了4 层,它可以有很多层。

    虚拟器上“霓虹灯”效果图

    现在,我们来看一下代码

    首先,要新建一个UIkit的工程

    建好工程后,我们要打开AppDelegate.swift文件,并在此文件中写入代码

    文件目录

    第一部分代码写在函数 application 中,代码如下:

    // 想在window对象添加内容,就在这个方法中实现

    //屏幕类

    //UIScreen.main获取屏幕对象

    //UIScreen.main.bounds 获取屏幕大小

    self.window = UIWindow(frame: UIScreen.main.bounds)//与模拟器设备适配

    self.window?.backgroundColor = UIColor.white

    self.window?.makeKeyAndVisible()//让window可见,并成为主屏幕

    self.window?.rootViewController = UIViewController()//给window设置根视图控制器

    //一般应用程序只有一个UIWindow对象。

    let redView = UIView(frame: CGRect(x: 107, y: 268, width: 200, height: 200))//添加视图

    redView.backgroundColor = UIColor.red//视图的背景颜色

    redView.tag = 200//tag值,属性,给视图添加唯一标识(0~100不可用)

    self.window?.addSubview(redView)//把redView添加到window

    redView.layer.cornerRadius = 100//切圆角半径100


    /*以下内容为添加的多层视图内容,可以依据需要增多添加视图*/

    let yellowView = UIView(frame: CGRect(x: 132, y: 293, width: 150, height: 150))

    yellowView.backgroundColor = UIColor.yellow

    yellowView.tag = 201

    self.window?.addSubview(yellowView)

    yellowView.layer.cornerRadius = 75

    let greenView = UIView(frame: CGRect(x: 157, y: 318, width: 100, height: 100))

    greenView.backgroundColor = UIColor.green

    greenView.tag = 202

    self.window?.addSubview(greenView)

    greenView.layer.cornerRadius = 50

    let purpleView = UIView(frame: CGRect(x: 182, y: 343, width: 50, height: 50))

    purpleView.backgroundColor = UIColor.purple

    purpleView.tag = 203

    self.window?.addSubview(purpleView)

    purpleView.layer.cornerRadius = 25

    /*以上内容为添加的多层视图内容,可以依据需要增多添加视图*/


    //设置定时器

    //参数一:定时执行的间隔

    //参数二:目标对象

    //参数三:目标对象选择执行方法

    //参数四:用户信息 nil

    //参数五:定时器是否重复执行

    Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(changeColor), userInfo: nil, repeats: true)

    /*第一部分代码完*/

    第二部分代码写在函数 application 外,代码如下:

    func changeColor() {

    let redView =  self.window?.viewWithTag(200)

    //存储redView的背景颜色

    let color = redView?.backgroundColor

    //多步赋值,改变颜色

    /*此处用到tag值,获取每一个视图的背景颜色,第一部分代码中,有几个视图,这一部分中就添加几步赋值*/

    self.window?.viewWithTag(200)?.backgroundColor = self.window?.viewWithTag(201)?.backgroundColor

    self.window?.viewWithTag(201)?.backgroundColor = self.window?.viewWithTag(202)?.backgroundColor

    self.window?.viewWithTag(202)?.backgroundColor = self.window?.viewWithTag(203)?.backgroundColor

    self.window?.viewWithTag(203)?.backgroundColor = color

    }

    /*第二部分代码完*/


    这就是今天的"闪闪"霓虹灯,大家多多尝试。

    相关文章

      网友评论

        本文标题:"闪闪"霓虹灯

        本文链接:https://www.haomeiwen.com/subject/yjhspttx.html