zoukankan      html  css  js  c++  java
  • swift中多继承的实现

    1. 实现过程

    swift本身并不支持多继承,但我们可以根据已有的API去实现. 

    swift中的类可以遵守多个协议,但是只可以继承一个类,而值类型(结构体和枚举)只能遵守单个或多个协议,不能做继承操作. 

    多继承的实现:协议的方法可以在该协议的extension中实现

    protocol Behavior {
        func run()
    }
    extension Behavior {
        func run() {
            print("Running...")
        }
    }
    
    struct Dog: Behavior {}
    
    let myDog = Dog()
    myDog.run() // Running...

    无论是结构体还是类还是枚举都可以遵守多个协议,所以多继承就这么做到了.

    2. 通过多继承为UIView扩展方法

    // MARK: - 闪烁功能
    protocol Blinkable {
        func blink()
    }
    extension Blinkable where Self: UIView {
        func blink() {
            alpha = 1
            
            UIView.animate(
                withDuration: 0.5,
                delay: 0.25,
                options: [.repeat, .autoreverse],
                animations: {
                    self.alpha = 0
            })
        }
    }
    
    // MARK: - 放大和缩小
    protocol Scalable {
        func scale()
    }
    extension Scalable where Self: UIView {
        func scale() {
            transform = .identity
            
            UIView.animate(
                withDuration: 0.5,
                delay: 0.25,
                options: [.repeat, .autoreverse],
                animations: {
                    self.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
            })
        }
    }
    
    // MARK: - 添加圆角
    protocol CornersRoundable {
        func roundCorners()
    }
    extension CornersRoundable where Self: UIView {
        func roundCorners() {
            layer.cornerRadius = bounds.width * 0.1
            layer.masksToBounds = true
        }
    }
    
    extension UIView: Scalable, Blinkable, CornersRoundable {}
    
     cyanView.blink()
     cyanView.scale()
     cyanView.roundCorners()
     

    来源:SwiftTips记录iOS开发中的一些知识点

  • 相关阅读:
    MySQL server version for the right syntax to use near ‘USING BTREE
    随笔
    [python]自问自答:python -m参数?
    [linux]查看linux下端口占用
    [linux]scp指令
    [编程题目]泥塑课
    How can I learn to program?
    [python]在场景中理解装饰器
    [前端]分享一个Bootstrap可视化布局的网站
    [python]python元类
  • 原文地址:https://www.cnblogs.com/chzheng/p/13304474.html
Copyright © 2011-2022 走看看