Как я могу добавить автоматические ограничения макета для линии программно

Я провел черту программно UI, Как я могу добавить ограничения для этой строки.

let line = UIView(frame: CGRect(x: 10, y: 350, width: 350, height: 1))
line.backgroundColor = UIColor.white;self.view.addSubview(line)

2 ответа

Решение

Я создал красную линию: высота = 1, верх = 50, и ширина будет гибкой. Вы можете изменить положение, как хотите.

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])
}

Результат!

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`
Другие вопросы по тегам