链式调用原理

常规写法:

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
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。