{
"$type": "site.standard.document",
"description": "Using anchors with Auto Layout is a big improvement over creating constraints using the class function in NSLayoutConstraint or Visual Format",
"path": "/overload-nslayoutconstraint-activate-arrays/",
"publishedAt": "2020-01-28T15:29:00.000Z",
"site": "at://did:plc:bryys25pc2fnagnyxqgsglhd/site.standard.publication/3mn26bjkkmh23",
"tags": [
"iOS Development",
"Swift",
"Techniques"
],
"textContent": "Using anchors with Auto Layout is a big improvement over creating constraints using the class function in NSLayoutConstraint or Visual Format Language. I don't use Interface Builder so I write all my layout in code. You also write your own wrappers to make creating multiple constraints easier, e.g one might write a function like NSLayoutConstraint.constraint(views:toSameWidth:) or NSLayoutConstraint.constraint(views:toSquareWithSides:), both returning an array.\n\nOr sometimes, in a more dynamic piece of UI, you might need to swap around arrays of constraints.\n\nI find it useful to define a protocol and a few extensions so that this can be done:\n\nNSLayoutConstraint.activate([\n constraintsArray1,\n constraintsArray2,\n constraint3,\n constraint4,\n constraint5,\n])\n\nAlternatives involve appending of arrays which ends up with code that is hard to indent.\n\nSo there you go:\n\nprotocol LayoutConstraintsWrapper {\n var constraints: [NSLayoutConstraint] { get }\n}\n\nextension Array: LayoutConstraintsWrapper where Element: NSLayoutConstraint {\n var constraints: [NSLayoutConstraint] {\n return self\n }\n}\n\nextension NSLayoutConstraint: LayoutConstraintsWrapper {\n var constraints: [NSLayoutConstraint] {\n return [self]\n }\n}\n\nextension NSLayoutConstraint {\n class func activate(_ constraints: [LayoutConstraintsWrapper]) {\n activate(constraints.flatMap { $0.constraints })\n }\n}",
"title": "Overload NSLayoutConstraint.activate to Accept Arrays as Elements"
}