链式调用原理

常规写法:

let subview = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
subview.backgroundColor = .red
subview.layer.masksToBounds = true
subview.layer.cornerRadius = 8
subview.isUserInteractionEnabled = true
self.addSubview(subview)

链式调用:

self.view.addSubview(
                    UIView()
                    .frame(CGRect(x: 0, y: 0, width: 100, height: 100))
                    .backgroundColor(.red)
                    .masksToBounds(true)
                    .cornerRadius(8)
                    .isUserInteractionEnabled(true)
                    )

实现原理:

调用方法之后返回自己,以实现链式调用

具体代码:

UIViewExtension.swift

extension UIView {
    public func frame(_ frame: CGRect) -> Self {
        self.frame = frame
        return self
    }
    
    public func isUserInteractionEnabled(_ isUserInteractionEnabled: Bool) -> Self {
        self.isUserInteractionEnabled = isUserInteractionEnabled
        return self
    }
    
    public func backgroundColor(_ backgroundColor: UIColor) -> Self {
        self.backgroundColor = backgroundColor
        return self
    }
}

你可能感兴趣的:(链式调用原理)