Search code examples
swiftautolayoutnslayoutconstraintsnapkit

How to set Multiplier of heightAnchor in SnapKit - swift


I am a new iOS programming. And i really enjoy this library of setting constraint of my views. But now i am coming with a doubt which in NSLayoutConstraint we can adjust height with multiplier of our main view. But i don't know how to achieve this in SnapKit.

Here what NSLayoutConstraint provides

NSLayoutConstraint.activate([
        cardViewInstance.mainCardView.topAnchor.constraint(equalTo: view.topAnchor, constant: marginOffset),
        cardViewInstance.mainCardView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
        cardViewInstance.mainCardView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
        cardViewInstance.mainCardView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1/5)
        ])

This what i have done with SnapKit

cardViewInstance.mainCardView.snp.makeConstraints { (make) in
        make.top.equalTo(view)
        make.topMargin.equalTo(marginOffset)

        make.leading.equalTo(self.view)
        make.leadingMargin.equalTo(20)

        make.trailing.equalTo(self.view)
        make.trailingMargin.equalTo(-20)


    }

Now i am stuck for setting height as multiplier of the main view.


Solution

  • You code in NSLayoutConstraint and code in SnapKit of setting constraint are not same when display.

    You know when you set cardViewInstance.mainCardView.topAnchor.constraint(equalTo: view.topAnchor, constant: marginOffset) its view will be stayed on top and padding from top as you have set in marginOffset. and in SnapKit you set

    make.top.equalTo(view) make.topMargin.equalTo(marginOffset)

    So, this is wrong because you cannot set top and topMargin at the same time because it not like what you have set in NSLayoutConstraint

    So please correct that with something like (according to document):

    make.top.equalTo(view).offset(marginOffset)
    

    For you question how to set multiplier you can achieve by declare a variable something like view.frame.height / 2 and you can apply in you SnapKit constraint make.height.equalTo(view.frame.height / 5)

    This is how the whole code look likes

    cardViewInstance.mainCardView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(marginOffset)
    
    
            make.leading.equalTo(self.view).offset(20)
    
    
            make.trailing.equalTo(self.view).offset(-20)
    
            make.height.equalTo(view.frame.height / 5)
    
        }
    

    Hope that help :D