• 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开发中的一些知识点

  • 相关阅读:
    从域名锁定该网站所在城市
    微信接口开发 2----接收微信接口返回的数据
    微信接口开发1--向微信发送请求--获取access_token
    MVC-前端设计
    MVC-第一个简单的程序
    MVC-基础02
    MVC-基础01
    表值函数
    视图

  • 原文地址:https://www.cnblogs.com/chzheng/p/13304474.html
Copyright © 2020-2023  润新知