I want to consolidate the NSLayoutDimension
NSLayoutXAxisAnchor
and NSLayoutYAxisAnchor
to create a wrapper for my anchors to avoid a long list of convenience methods
The ideal syntax I was looking for was
extension UIView {
func example() {
attach("width" to:view, "height")
}
func attach(_ value:String to view:UIView, _ otherValue:String) -> NSLayoutConstraint {
let firstAnchor = anchor(for:value)
let secondAnchor = anchor(for:otherValue)
return firstAnchor.match(view.secondAnchor)
}
// My original expectation for generics
func anchor<A: NSLayoutAnchor<AnyObject>>(for string:String) -> A {
switch string {
case "height":
return heightAnchor
default:
return widthAnchor
}
// etc....
}
extension NSLayoutAnchor {
func match(_ anchor:NSLayoutAnchor) -> NSLayoutConstraint {
return constraint(equalTo: view.anchor)
}
}
The closest I seem to be able to get to is...
func equivalent(_ dimension: NSLayoutDimension) -> NSLayoutDimension {
switch dimension {
case heightAnchor:
return heightAnchor
default:
return widthAnchor
}
}
But here is where I'm getting a bit lost... this isn't really achieving much... ideally I'd want to fetch all of the Anchors in one place i.e. expand equivalent
so that I can easily access anchors based on the same query..
this is possible with NSLayoutAttribute
func attribute(for string:String) -> NSLayoutAttribute {
switch string {
case "left":
return .left
case "right":
return .right
however it doesn't work with the generics as I have them above... I know the syntax is wrong and that anchors are properties on the UIView
s but I'm not sure how to fix it...
Thanks for your time