2

I drew a line programatically in y UI. How can I add constraints for this line.

let line = UIView(frame: CGRect(x: 10, y: 350, width: 350, height: 1))
line.backgroundColor = UIColor.white;self.view.addSubview(line)
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
faheem
  • 83
  • 12

2 Answers2

2

I created a red line: height = 1, top = 50 and the width will be flexible You can modify the position as you want.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let line = UIView()
    line.backgroundColor = UIColor.red
    view.addSubview(line)

    line.translatesAutoresizingMaskIntoConstraints = false

    let leadingConstraint = NSLayoutConstraint(item: line, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 20.0)
    let topConstraint = NSLayoutConstraint(item: line, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 50.0)
    let trailingConstraint = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: line, attribute: .right, multiplier: 1.0, constant: 20.0)
    let heightConstraint = NSLayoutConstraint(item: line, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 1.0)

    view.addConstraints([topConstraint, leadingConstraint, trailingConstraint, heightConstraint])
}

The result!

enter image description here

Danh Huynh
  • 2,337
  • 1
  • 15
  • 18
1

NSLayoutConstraint Style

NSLayoutConstraint(item: line, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: line, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0).active = true`
tabassum
  • 1,100
  • 6
  • 17
  • Thanks for a quick response. But this is not making any changes to the line. if i change the model in simulator, the line is not appearing in the same place.@tabassum – faheem Mar 28 '17 at 06:16