NSDictionaryOfVariableBindings is, as you say, a macro. There are no macros in Swift. So much for this.
However, you can easily write a Swift function to assign line names to your views in a dictionary, and then pass that dictionary to constraintsWithVisualFormat . The difference is that, unlike Objective-C, Swift cannot see your names for these views; you will have to allow him to create new names.
[To be clear, this does not mean that your Objective-C code could see your variable names; this is that during the macro evaluation, the preprocessor worked on your source code as text and rewrote it - and so it could just use the text of your variable names both inside quotation marks (to create strings) and outside (to create values) to form a dictionary. But with Swift there is no preprocessor.]
So here is what I am doing:
func dictionaryOfNames(arr:UIView...) -> Dictionary<String,UIView> { var d = Dictionary<String,UIView>() for (ix,v) in arr.enumerate(){ d["v\(ix+1)"] = v } return d }
And you name it and use it like this:
let d = dictionaryOfNames(myView, myOtherView, myFantasicView) myView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|[v2]|", options: nil, metrics: nil, views: d) )
The trick is that it is up to you to decide that the name for myOtherView in your visual format string will be v2 (since it was second in the list passed to dictionaryOfNames() ). But I can live with it simply to avoid the tedious manual printing of the dictionary every time.
Of course, you could equally well write more or less the same function in Objective-C. It’s just that you weren’t worried because the macro already existed!
matt Jul 06 '14 at 1:48 2014-07-06 01:48
source share