Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for Swift 3 AddConstraintWithFormat?

Tags:

ios

swift

I found sourcode:

view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
view.addConstraintsWithFormat("V:|[v0(50)]", views: menuBar)

And I'm using Swift 3, it's not working in my Xcode 8

Can someone tell me what code for that ?

Thank you so much!

like image 785
Menda Avatar asked Feb 16 '17 03:02

Menda


2 Answers

You should write a function like this:

   func addContraintsWithFormat(_ format: String, views: UIView...) {
        var viewDict = [String: UIView]()

        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewDict[key] = view
        }

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
    }

It would work for you!

May be you need Visual Format Language to use this function.

like image 195
javimuu Avatar answered Oct 14 '22 09:10

javimuu


You have to write extension for UIView. Something like that:

extension UIView {
    func addConstraintsWithFormat(_ format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()
        for (index, view) in views.enumerated() {
            let key = "v\(index)"
            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
    }
}
like image 43
jMelvins Avatar answered Oct 14 '22 09:10

jMelvins