Если я хочу создать эти ограничения программно, как это сделать?
У меня есть UITableView с этими ограничениями. Я пытаюсь создать UITableView программно, но все же хочу, чтобы эти ограничения были в коде.
Если я хочу создать эти ограничения программно, как это сделать?
У меня есть UITableView с этими ограничениями. Я пытаюсь создать UITableView программно, но все же хочу, чтобы эти ограничения были в коде.
Вы можете сделать это довольно легко с помощью визуального языка формата:
Добавить Ваш взгляд, topLayoutGuide
и bottomLayoutGuide
к словарю. Я использовал views
. Вы также должны установить translatesAutoresizingMaskIntoConstraints
на false
за ограничения на работу.
Пример:
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[yourView]-(-15)-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayout][yourView][botLayout]", options: [], metrics: nil, views: views))
один из способов сделать это:
let newView = UIView()
newView.backgroundColor = UIColor.redColor()
newView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(newView)
let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -15)
view.addConstraint(verticalConstraint)
let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(heightConstraint)
для получения дополнительной информации вы можете следовать этому Swift | Adding constraints programmatically
смотри раздел 'NSLayoutConstraints' здесь -> https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW1 – Adrian