程序员

RxSwift系列后续

2018-06-12  本文已影响15人  ripple_k
class VCutCollectionViewCell: UICollectionViewCell {
    
    let imageView = UIImageView()
    let playButton = UIButton(type: .custom)
    let disposeBag = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView
            .soap.adhere(toSuperView: contentView)
            .soap.config { (imageView) in
                imageView.contentMode = .scaleAspectFit
                imageView.clipsToBounds = true
                imageView.isUserInteractionEnabled = true
            }
            .soap.layout { (make) in
                make.edges.equalTo(contentView)
            }
        
        playButton
            .soap.adhere(toSuperView: contentView)
            .soap.config { (button) in
                button.frame.size = CGSize(width: 60, height: 60)
                button.setBackgroundImage(#imageLiteral(resourceName: "lightbox_play"), for: UIControlState())
                
                button.layer.shadowOffset = CGSize(width: 1, height: 1)
                button.layer.shadowColor = UIColor.gray.cgColor
                button.layer.masksToBounds = false
                button.layer.shadowOpacity = 0.8
            }
            .soap.layout { (make) in
                make.center.equalTo(contentView)
            }
            .rx.tap.asObservable()
            .subscribe(onNext: { (_) in
                print("tap...")
            })
            .disposed(by: disposeBag)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

这样写代码是不是很爽?? O(∩_∩)O哈哈~
来看一下是怎么实现的吧

首先是一个命名空间的语法糖

public protocol NamespaceWrappable {
    associatedtype SoapWrapperType
    var soap: SoapWrapperType { get }
    static var soap: SoapWrapperType.Type { get }
}

public extension NamespaceWrappable {
    var soap: NamespaceWrapper<Self> {
        return NamespaceWrapper(value: self)
    }

    static var soap: NamespaceWrapper<Self>.Type {
        return NamespaceWrapper.self
    }
}

public struct NamespaceWrapper<T> {
    public let wrappedValue: T
    public init(value: T) {
        self.wrappedValue = value
    }
}

接下来就是针对这个命名空间里的UIView的扩展啦。。。

extension UIView: NamespaceWrappable { }
extension NamespaceWrapper where T: UIView {
    public func adhere(toSuperView: UIView) -> T {
        toSuperView.addSubview(wrappedValue)
        return wrappedValue
    }

    @discardableResult
    public func layout(snapKitMaker: (ConstraintMaker) -> Void) -> T {
        wrappedValue.snp.makeConstraints { (make) in
            snapKitMaker(make)
        }
        return wrappedValue
    }

    @discardableResult
    public func config(_ config: (T) -> Void) -> T {
        config(wrappedValue)
        return wrappedValue
    }
}
上一篇下一篇

猜你喜欢

热点阅读