0

I come from front-end development, when I create div it automatically displays itself in top, after second one it will display itself below the first one, and so...

I want to be able to do the same with swift UIViews, I've created some views and want to add constraints automatically after previous view, and if the view is the first one apply it to the parent view, how do I do it any suggestions? I have created custom class from UIView called Car, but then I realized it was not a good idea

if let parent = self.superview {
        let siblings = parent.subviews.filter{$0 is Car}
        let lastCar: UIView?
        if siblings.count > 1{
            lastCar = siblings[siblings.count - 2]
        } else {
            lastCar = nil
        }
        if let sibling = lastCar {
            parent.addConstraint(
                NSLayoutConstraint(
                    item: self,
                    attribute: .Top,
                    relatedBy: .Equal,
                    toItem: sibling,
                    attribute: .Bottom,
                    multiplier: 1.0,
                    constant: 1
                ))
        } else {
            parent.addConstraint(
                NSLayoutConstraint(
                    item: self,
                    attribute: .Top,
                    relatedBy: .Equal,
                    toItem: parent,
                    attribute: .Top,
                    multiplier: 1.0,
                    constant: 0
                ))
        }
    }

I set the constraints to lastCar or parent view using if let syntax.

nikagar4
  • 830
  • 4
  • 11
  • 23
  • Possible duplicate of [SWIFT | Adding constraints programmatically](http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically) – BallpointBen Apr 27 '16 at 08:18
  • Looks like you're on the right track. You'll need constraints specifying the left/right (or width) as well. What problem are you running into? – jtbandes Apr 27 '16 at 08:42
  • I haven't ran to a problem but i want to be sure that it wont crash, this app is gonna represent big company in my country so i want it to work smoothly without any problems – nikagar4 Apr 27 '16 at 09:54

0 Answers0