Swift(三)自定义控件---UISwitch

@TOC

需求分析

  1. 项目中有一个UI页面需要用到自定义UISwitch控件,页面如图:


    在这里插入图片描述
  2. 这里有两个需求,一个是播放gif动画:实现参考: swift 播放GIF;另外一个就是定义UISwitch.
  3. demo 下载地址:Swift 实现自定义控件

实现自定义UISwich控件

1. 实现代码

//
//  KYLCustomSwitch.swift
//  
//
//  Created by yulu kong on 2019/7/16.
//  Copyright © 2019 ubt. All rights reserved.
//

import Foundation
import UIKit

/// 开关点击事件
typealias KYLSwitchValueChange = (Bool) -> ()

struct KYLSwitchConfig {
    
    /// 关闭背景颜色
    var offBgColor = UIColor(red: 0 / 255.0, green: 0 / 255.0, blue: 0 / 255.0, alpha: 0.2)
    /// 打开背景颜色
    var onBgColor = UIColor(red: 70 / 255.0, green: 0 / 255.0, blue: 3 / 255.0, alpha: 1)
    
    /// 关闭圆点颜色
    var offPointColor = UIColor(red: 153 / 255.0, green: 153 / 255.0, blue: 153 / 255.0, alpha: 1)
    /// 打开圆点颜色
    var onPointColor = UIColor(red: 158 / 255.0, green: 0 / 255.0, blue: 6 / 255.0, alpha: 1)
    
    /// 关闭背景图片
    var offBgImage: UIImage?
    /// 打开背景图片
    var onBgImage: UIImage?
    
    /// 关闭圆点图片
    var offPointImage: UIImage?
    /// 打开圆点图片
    var onPointImage: UIImage?
    
    /// 背景View的上下边距
    var bgMargin: CGFloat = 0
    
    /// 圆点的上下边距
    var pointMargin: CGFloat = 5
}

class KYLCustomSwitch: UIControl {
    
    /// 背景View
    var bgView: UIView!
    
    /// 开关圆点View
    var pointView: UIView!
    
    /// 配置
    var config: KYLSwitchConfig!{
        didSet{
            updateUI()
        }
    }
    
    var  valueChangedHandle: KYLSwitchValueChange?
    
    /// 开关状态
    var isOn: Bool = false {
        didSet{
            updateUI()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 底部背景
        bgView = UIView()
        addSubview(bgView)
        bgView.layer.masksToBounds = true
        bgView.isUserInteractionEnabled = false
        
        // 开关按钮
        pointView = UIView()
        addSubview(pointView)
        pointView.layer.masksToBounds = true
        pointView.isUserInteractionEnabled = false
        config = KYLSwitchConfig()
        
        addTarget(self, action: #selector(stateChanges), for: .touchUpInside)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 布局
        bgView.frame = CGRect(x: 0, y: config.bgMargin, width: frame.width, height: frame.height - config.bgMargin * 2)
        
        updateUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 响应事件
    @objc func stateChanges() {
        isOn ? changeToOffAnimation() : changeToOnAnimation()
        isOn = !isOn
        valueChangedHandle?(isOn)
    }
    
}

// MARK: - UI 逻辑
extension KYLCustomSwitch {
    /// 设置圆角和背景色
    func updateUI() {
        
        bgView.layer.cornerRadius = (frame.height - config.bgMargin * 2) * 0.5
        bgView.backgroundColor = config.offBgColor
        pointView.layer.cornerRadius = (frame.height - config.pointMargin * 2) * 0.5
        pointView.backgroundColor = config.offPointColor
        
        let pointWidth = frame.height - config.pointMargin * 2
        if isOn {
            pointView.frame = CGRect(x: bgView.frame.maxX - pointView.frame.width - config.pointMargin, y: config.pointMargin, width: pointWidth, height: pointWidth)
            changeToOnPointViewStyle()
        }
        else {
            pointView.frame = CGRect(x: bgView.frame.minX + config.pointMargin, y: config.pointMargin, width: pointWidth, height: pointWidth)
            changeToOffPointViewStyle()
        }
    }
    
    private func changeToOnAnimation() {
        var frame: CGRect = pointView.frame
        frame.origin.x = bgView.frame.minX + config.pointMargin
        
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.pointView.frame = frame
            strongSelf.changeToOffPointViewStyle()
        })
    }
    
    
    private func changeToOffAnimation() {
        var frame: CGRect = pointView.frame
        frame.origin.x = bgView.frame.maxX - pointView.frame.width - config.pointMargin
        
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            guard let strongSelf = self else {
                return
            }
            strongSelf.pointView.frame = frame
            strongSelf.changeToOnPointViewStyle()
        })
    }
    
    private func changeToOnPointViewStyle() {
        bgView.backgroundColor = config.onBgColor
        pointView.backgroundColor = config.onPointColor
        if let img = config.onPointImage {
            pointView.layer.contents = img.cgImage
        }
        if let bgImg = config.onBgImage {
            bgView.layer.contents = bgImg.cgImage
        }
    }
    
    private func changeToOffPointViewStyle() {
        bgView.backgroundColor = config.offBgColor
        self.pointView.backgroundColor = config.offPointColor
        if let img = config.offPointImage {
            pointView.layer.contents = img.cgImage
        }
        if let bgImg = config.offBgImage {
            bgView.layer.contents = bgImg.cgImage
        }
    }
}

//测试1

//测试2

2. 测试代码

//
//  ViewController.swift
//  kyl_swift_UIDemo
//
//  Created by yulu kong on 2019/7/16.
//  Copyright © 2019 yulu kong. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var customSwitch: KYLCustomSwitch!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        testSwitch()
    }
    
    private func testSwitch() {
        self.customSwitch = KYLCustomSwitch()
        self.view.addSubview(customSwitch)
        customSwitch.center = self.view.center
        customSwitch.bounds = CGRect(x: 0, y: 0, width: 200, height: 60)
        customSwitch.valueChangedHandle = {(isOn) in
            print(isOn)
        }
        
        var config = KYLSwitchConfig()
        config.offBgColor = UIColor(hex: 0xE9E9F2, alpha: 1.0)
        config.onPointImage = UIImage(named: "icon_switch_turn")
        config.offPointImage = UIImage(named: "icon_switch_angle")
        customSwitch.config = config
    }


}


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,576评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,515评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,017评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,626评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,625评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,255评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,825评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,729评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,271评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,363评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,498评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,183评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,867评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,338评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,458评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,906评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,507评论 2 359

推荐阅读更多精彩内容

  • 你有没有过当一个自由职业者的梦想?工作时间地点自由、做着自己喜欢的事情的同时,还能赚到钱,活得很滋润。想想是不是美...
    预约晴天阅读 169评论 0 0
  • (一) 血,让人望而惊恐,谈及忌讳,更让人联想到宝贵的生命。见到血,我也很怕! 几年前,看到城市广场的采血车和流动...
    谭惜之阅读 634评论 2 1
  • 近段时间,我时常可以想起之前我在博客里看到的一句话“成长,大概就是接受月亮也有背面的事实。”我常常在不断地尝试和更...
    阿雅克肖Aay阅读 707评论 0 0