gsdios / SDAutoLayout

One line of code to implement automatic layout. 一行代码搞定自动布局!支持Cell和Tableview高度自适应,Label和ScrollView内容自适应,致力于做最简单易用的AutoLayout库。The most easy way for autoLayout. Based on runtime.
MIT License
5.9k stars 1.28k forks source link

更新SDAutoLayout的Swift扩展,使用Swifty风格的点语法实现SDAutoLayout布局 #316

Open fanyuexiang opened 5 years ago

fanyuexiang commented 5 years ago

before

extension UIView {
    @discardableResult
    public func layout() -> SDAutoLayoutModel {
        return sd_layout()
    }
}

// example:not swifty and the function name 'layout()' is easy to repeat
yourView.layout()
   .topTo(view, 10)
   .leftTo(view, 10)
   .width(is: 100)
   .height(is: 100)

now

public final class SDAutoLayout<Base> {
    public let base: Base
    public init(_ base: Base) {
        self.base = base
    }
}

public protocol SDAutoLayoutCompatible {
    associatedtype CompatibleType
    var sd: CompatibleType { get }
}

public extension SDAutoLayoutCompatible {
    var sd: SDAutoLayout<Self> {
        get { return SDAutoLayout(self) }
    }
}

extension UIView: SDAutoLayoutCompatible { }

extension SDAutoLayout where Base: UIView {
    @discardableResult
    public func layout() -> SDAutoLayoutModel {
        return base.sd_layout();
    }
}

// example:  swifty 🎉🎉🎉
yourView.sd.layout()
       .topTo(view, 10)
       .leftTo(view, 10)
       .width(is: 100)
       .height(is: 100)