协议和扩展

2020-02-18  本文已影响0人  toro宇

Swift Extension 添加存储属性

wift不允许在extension中直接添加「存储属性」。但是在我们的实际开发中经常会用到使用extension来给已经创建好的类添加新的「存储属性」。例如,给UIView类添加一个identifier属性来区别不同UIView实例。

如果直接在UIView的extension中添加,编译器会报Extensions must not contain stored properties。如下图:


既然不能直接定义存储属性identifier,我们可以使用关联属性来实现想要的功能。代码如下:

  
public extension UIView {
    private struct AssociatedKey {
        static var identifier: String = "identifier"
    }
    
    public var identifier: String {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.identifier) as? String ?? ""
        }
        
        set {
            objc_setAssociatedObject(self, &AssociatedKey.identifier, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
}
    import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view's identifier:\(self.view.identifier)")
        view.identifier = "root view"
        print("view's identifier:\(self.view.identifier)")
    }
}

Result: ----------------------
view's identifier:
view's identifier:root view

使用 protocol来声明协议。

  protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

类,枚举以及结构体都兼容协议。
协议类似java中的接口 通过定义共有的属性和方法,然后实现。 变相实现了多继承

    class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
 
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

注意使用 mutating关键字来声明在 SimpleStructure中使方法可以修改结构体。在 SimpleClass中则不需要这样声明,因为类里的方法总是可以修改其自身属性的。

使用 extension来给现存的类型增加功能,比如说新的方法和计算属性。你可以使用扩展来使协议来别处定义的类型,或者你导入的其他库或框架。

    extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)

通过扩展给UIButton 加block事件回调

  // MARK: - 快速设置按钮 并监听点击事件
typealias  buttonClick = (()->()) // 定义数据类型(其实就是设置别名)
extension UIButton {
    // 改进写法【推荐】
    private struct HWRuntimeKey {
        static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
        static let delay = UnsafeRawPointer.init(bitPattern: "delay".hashValue)
        /// ...其他Key声明
    }
    /// 运行时关联
    private var actionBlock: buttonClick? {
        set {
            objc_setAssociatedObject(self, UIButton.HWRuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, UIButton.HWRuntimeKey.actionBlock!) as? buttonClick
        }
    }
    private var delay: TimeInterval {
        set {
            objc_setAssociatedObject(self, UIButton.HWRuntimeKey.delay!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, UIButton.HWRuntimeKey.delay!) as? TimeInterval ?? 0
        }
    }
    /// 点击回调
    @objc private func tapped(button:UIButton) {
        actionBlock?()
        isEnabled = false
        // 4.GCD 主线程/子线程
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in // 延迟调用方法
            DispatchQueue.main.async { // 不知道有没有用反正写上就对了
                print("恢复时间\(Date())")
                self?.isEnabled = true
            }
        }
    }
    /// 添加点击事件
    func addAction(_ delay: TimeInterval = 0, action:@escaping buttonClick) {
        addTarget(self, action:#selector(tapped(button:)) , for:.touchUpInside)
        self.delay = delay
        actionBlock = action
    }
}

使用

              btn.addAction { // 不加延迟时间
            print("点击按钮")
        }
        btn.addAction(3) { [weak self] in // 延迟3秒才可点击
            self?.label.text = "\(Date())"
            print("点击时间\(Date())")
        }
        btn1.addAction(10) { [weak self] in // 延迟10秒才可点击
            self?.label1.text = "\(Date())"
            print("点击时间\(Date())")
        }
上一篇 下一篇

猜你喜欢

热点阅读