iOS 关于UIResponder思考

  • UIResponder 方式

    • 通过UIResponder的方式将各个节点绑定起来,只能通过父子关系绑定. 而且父视图的事件不能引发子视图的相应。
    • 通过view的 nextResponder 还可以查找所在的VC

代码

extension UIResponder {
    @objc func responder(eventName: String, userInfo: String) {
        print("Responder的对象: \(type(of: self))")
        self.next?.responder(eventName: eventName, userInfo: userInfo)
    }
}
  • 自定义链表方式

    • 不管从链表中哪个节点发送事件,它都要先找到链表头部节点(做成双向链表,也是方便查找头部节点),然后从头节点开始相应事件。

代码

    var headerNode: BindResponderOfChain?
    var lastNode: BindResponderOfChain? {
        guard var node = headerNode else { return nil }
        while let next = node.nextChain {
            node = next
        }
        return node
    }
    var prevChain: BindResponderOfChain?
    var nextChain: BindResponderOfChain?
    
    func initWith(closure: (BindResponderOfChain) -> Void) {
        closure(self)
    }
    
    func next(_ node: BindResponderOfChain) -> BindResponderOfChain {
        self.nextChain = node
        if let last = lastNode {
            last.nextChain = node
            node.prevChain = last
        } else {
            headerNode = node
        }
        return self
    }
    
    func getChainList() -> [BindResponderOfChain]{
        var nodes = [BindResponderOfChain]()
        var temp = self.headerNode
        while temp != nil {
            nodes.append(temp!)
            temp = temp!.nextChain
        }
        return nodes
    }
    
    func cutOffChain() -> Bool{
        return false
    }
    
    func sendEvent(eventType: NSInteger, with item: BlockModel) {
        var temp = self
        while (temp.prevChain != nil) {
            if (temp.prevChain == nil) {
                break
            }
            temp = temp.prevChain!
        }
        temp.responseEvent(eventType: eventType, with: item )
    }

    func responseEvent(eventType: NSInteger, with item: BlockModel) {
        print("log: \(type(of: self))" + "\(eventType)" + "\(item)")
    }
}