Post marked as solved
Post marked as solved with 2 replies, 801 views
Hi! I'm trying to create an extension to reduce work when use View Code. I've just been in a lab but they couldn't had enough time to fully solve my problem.
So, before the lab I had:
extension UIView {
func fix(in otherView: UIView, to side: ConstraintType, with	constant: CGFloat) -> NSLayoutConstraint {
switch side {
case .top:
return self.topAnchor.constraint(equalTo: otherView.topAnchor, constant: constant)
case .bottom:
return self.bottomAnchor.constraint(equalTo: otherView.bottomAnchor, constant: constant)
case .left:
return self.leftAnchor.constraint(equalTo: otherView.leftAnchor, constant: constant)
case .right:
return self.rightAnchor.constraint(equalTo: otherView.rightAnchor, constant: constant)
case .centerX:
return self.centerXAnchor.constraint(equalTo: otherView.centerXAnchor, constant: constant)
case .centerY:
return self.centerYAnchor.constraint(equalTo: otherView.centerYAnchor, constant: constant)
default: return NSLayoutConstraint()
}
}
}
public enum ConstraintType {
case top, bottom, left, right, centerX, centerY
}
It works, but it's too big and, in this case, I only have one side (for both views). If I added the side of the other view, this will be huge..
After the lab, I got this:
extension UIView {
func fix(in otherView: UIView, to side: ConstraintType, with constant: CGFloat) -> NSLayoutConstraint {
return side.getAnchor(view: self).constraint(equalTo: side.getAnchor(view: otherView))
}
}
protocol ConstraintType {
func getAnchor(view: UIView) -> Anchor
associatedtype Anchor
}
public enum ConstraintYType: ConstraintType {
typealias Anchor = NSLayoutYAxisAnchor
case bottom, top, centerY
func getAnchor(view: UIView) -> Anchor {
switch self {
case .bottom:
return view.centerYAnchor
case .top:
return view.topAnchor
case .centerY:
return view.centerYAnchor
}
}
}
public enum ConstraintXType: ConstraintType {
typealias Anchor = NSLayoutXAxisAnchor
case left, right, centerX
func getAnchor(view: UIView) -> Anchor {
switch self {
case .left:
return view.leftAnchor
case .right:
return view.rightAnchor
case .centerX:
return view.centerXAnchor
}
}
}
It's really better! But, I'm getting an error:
Protocol 'ConstraintType' can only be used as a generic constraint because it has Self or associated type requirements
and...
Member 'getAnchor' cannot be used on value of protocol type 'ConstraintType'; use a generic constraint instead
So, now my question is: how can I fix it or do it in other way?