churabou / iOS-develop-blog

0 stars 0 forks source link

5月6日(日) NSLayoutAnchorを自分でExtensionしようとしたら、ジェネリクスの勉強になりそう。 #22

Open churabou opened 6 years ago

churabou commented 6 years ago

qiita

いつもSnapKit使ってあんまり使わないけど

        blue.widthAnchor.constraint(equalToConstant: 100).isActive = true
        blue.heightAnchor.constraint(equalToConstant: 300).isActive = true
        blue.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        blue.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 30).isActive = true

全体

class View: UIView {

    private var blue = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        blue.backgroundColor = .blue
        blue.translatesAutoresizingMaskIntoConstraints = false
        addSubview(blue)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func updateConstraints() {
        blue.widthAnchor.constraint(equalToConstant: 100).isActive = true
        blue.heightAnchor.constraint(equalToConstant: 300).isActive = true
        blue.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        blue.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 30).isActive = true
        super.updateConstraints()
    }
}
churabou commented 6 years ago

さすがに isActive = trueくらい・・

こんな感じにSnapKitみたいExtensionしてみる。

        blue.layout { (layout) in
            layout.width.equal(to: 200)
            layout.height.equal(to: 300)
            layout.centerX.equal(to: self)
            layout.centerY.equal(to: self)
        }

と思ったらジェネリクスにつまずいた。 今は時間がないが勉強のいいネタになる。

とりあえず各anchorのショートカット作成

class Anchor {

    private var view: UIView
    init(_ view: UIView) {
        self.view = view
    }

    var width: NSLayoutDimension {
        return view.widthAnchor
    }

    var height: NSLayoutDimension {
        return view.heightAnchor
    }

    var top: NSLayoutYAxisAnchor {
        return view.topAnchor
    }

    var bottom: NSLayoutYAxisAnchor {
        return view.bottomAnchor
    }

    var left: NSLayoutXAxisAnchor {
        return view.leftAnchor
    }

    var right: NSLayoutXAxisAnchor {
        return view.rightAnchor
    }

    var centerX: NSLayoutXAxisAnchor {
        return view.centerXAnchor
    }

    var centerY: NSLayoutYAxisAnchor {
        return view.centerYAnchor
    }
}

extension UIView {
    func layout(_ closure: ((Anchor)->Swift.Void)) {
        closure(Anchor(self))
    }
}

equal(to )を追加


extension NSLayoutDimension {

    func equal(to: CGFloat) {
        self.constraint(equalToConstant: to).isActive = true
    }
}

extension NSLayoutXAxisAnchor {

    func equal(to: UIView) {
        self.constraint(equalTo: to.centerXAnchor).isActive = true
    }
}

extension NSLayoutYAxisAnchor {

    func equal(to: UIView) {
        self.constraint(equalTo: to.centerYAnchor).isActive = true
    }
}