Como adicionar restrições programaticamente usando o Swift

Estou tentando descobrir isso desde a semana passada, sem dar mais nenhum passo adiante. Ok, então eu preciso aplicar algumas restrições programaticamente no Swift para um UIView usando este código:

 var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100)); new_view.backgroundColor = UIColor.redColor(); view.addSubview(new_view); var constX:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0); self.view.addConstraint(constX); var constY:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0); self.view.addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0); self.view.addConstraint(constW); var constH:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0); self.view.addConstraint(constH); 

Mas o Xcode retorna essa saída estranha:

 2014-10-03 09:48:12.657 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "" ) Will attempt to recover by breaking constraint  Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in  may also be helpful. 2014-10-03 09:48:12.658 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "" ) Will attempt to recover by breaking constraint  Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in  may also be helpful. 

Pode me ajudar? Muito obrigado

Você planeja ter um UIView quadrado de largura: 100 e Altura: 100 centrado dentro do UIView de um UIViewController ? Em caso afirmativo, você pode tentar um dos 6 seguintes estilos de layout automático (Swift 4 / iOS 11):


1. Usando o inicializador NSLayoutConstraint

 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100) let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100) view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100) let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true } 

2. Usando o Visual Format Language

 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let views = ["view": view!, "newView": newView] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=0)-[newView(100)]", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: views) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=0)-[newView(100)]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views) view.addConstraints(horizontalConstraints) view.addConstraints(verticalConstraints) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let views = ["view": view!, "newView": newView] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=0)-[newView(100)]", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: views) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=0)-[newView(100)]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views) NSLayoutConstraint.activate(horizontalConstraints) NSLayoutConstraint.activate(verticalConstraints) } 

3. Usando uma mistura de inicializador NSLayoutConstraint e linguagem de formato visual

 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let views = ["newView": newView] let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) view.addConstraints(widthConstraints) view.addConstraints(heightConstraints) view.addConstraints([horizontalConstraint, verticalConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let views = ["newView": newView] let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) NSLayoutConstraint.activate(widthConstraints) NSLayoutConstraint.activate(heightConstraints) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let views = ["newView": newView] let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) NSLayoutConstraint.activate(widthConstraints) NSLayoutConstraint.activate(heightConstraints) NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true } 

4. Usando UIViewAutoresizing

Nota: Molas e Struts serão traduzidos em restrições de layout automático correspondentes no tempo de execução.

 override func viewDidLoad() { let newView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = true newView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) newView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin] } 

5. Usando NSLayoutAnchor

 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor) let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100) let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100) view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor) let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100) let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint]) } 
 override func viewDidLoad() { let newView = UIView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false newView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true newView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true newView.widthAnchor.constraint(equalToConstant: 100).isActive = true newView.heightAnchor.constraint(equalToConstant: 100).isActive = true } 

6. Usando intrinsicContentSize e NSLayoutAnchor

 import UIKit class CustomView: UIView { override var intrinsicContentSize: CGSize { return CGSize(width: 100, height: 100) } } class ViewController: UIViewController { override func viewDidLoad() { let newView = CustomView() newView.backgroundColor = UIColor.red view.addSubview(newView) newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint]) } } 

Isso me ajuda a aprender visualmente, então esta é uma resposta suplementar.

Código boilerplate

 override func viewDidLoad() { super.viewDidLoad() let myView = UIView() myView.backgroundColor = UIColor.blue myView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(myView) // Add constraints code here // ... } 

Cada um dos exemplos a seguir é independente dos outros.

Pin borda esquerda

myView.leading = leadingMargin + 20

insira a descrição da imagem aqui

Método 1: estilo âncora

 let margins = view.layoutMarginsGuide myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20).isActive = true 
  • Além do leadingAnchor , há também o trailingAnchor , topAnchor e bottomAnchor .

Método 2: estilo NSLayoutConstraint

 NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1.0, constant: 20.0).isActive = true 
  • Além de .leading há também .trailing , .top e .bottom .
  • Além de .leadingMargin há também .trailingMargin , .topMargin e .bottomMargin .

Definir Largura e Altura

width = 200
height = 100

insira a descrição da imagem aqui

Método 1: estilo âncora

 myView.widthAnchor.constraint(equalToConstant: 200).isActive = true myView.heightAnchor.constraint(equalToConstant: 100).isActive = true 

Método 2: estilo NSLayoutConstraint

 NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true 

Centro no contêiner

myView.centerX = centerX
myView.centerY = centerY

insira a descrição da imagem aqui

Método 1: estilo âncora

 myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 

Método 2: estilo NSLayoutConstraint

 NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true 

Notas

  • O estilo de âncora é o método preferido em relação ao NSLayoutConstraint Style, no entanto, ele só está disponível no iOS 9, portanto, se você estiver suportando o iOS 8, ainda deverá usar o Estilo NSLayoutConstraint .
  • Os exemplos acima mostraram apenas uma ou duas restrições que estavam sendo focalizadas. No entanto, para colocar corretamente o myView no meu projeto de teste, eu precisava ter quatro restrições.

Leitura Adicional

  • Programaticamente criando documentação de restrições

Se você quiser preencher sua super visão, sugiro a maneira mais veloz:

  view.translatesAutoresizingMaskIntoConstraints = false let attributes: [NSLayoutAttribute] = [.top, .bottom, .right, .left] NSLayoutConstraint.activate(attributes.map { NSLayoutConstraint(item: view, attribute: $0, relatedBy: .equal, toItem: view.superview, attribute: $0, multiplier: 1, constant: 0) }) 

De outro modo, se você precisar de restrições não iguais, confira o NSLayoutAnchor no iOS 9. É muito mais fácil ler isso usando o NSLayoutConstraint diretamente:

  view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: view.superview!.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: view.superview!.bottomAnchor).isActive = true view.leadingAnchor.constraint(equalTo: view.superview!.leadingAnchor, constant: 10).isActive = true view.trailingAnchor.constraint(equalTo: view.superview!.trailingAnchor, constant: 10).isActive = true 

O problema, como a mensagem de erro sugere, é que você tem restrições do tipo NSAutoresizingMaskLayoutConstraints que entram em conflito com suas restrições explícitas, porque new_view.translatesAutoresizingMaskIntoConstraints é definido como true.

Essa é a configuração padrão das visualizações criadas no código. Você pode desligá-lo assim:

 var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100)) new_view.translatesAutoresizingMaskIntoConstraints = false 

Além disso, suas restrições de largura e altura são estranhas. Se você quiser que a visão tenha uma largura constante, esta é a maneira correta:

 new_view.addConstraint(NSLayoutConstraint( item:new_view, attribute:NSLayoutAttribute.Width, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute, multiplier:0, constant:100)) 

(Substitua 100 pela largura que você quer que ele tenha.)

Se o seu destino de implementação for o iOS 9.0 ou posterior, você poderá usar esse código mais curto:

 new_view.widthAnchor.constraintEqualToConstant(100).active = true 

De qualquer forma, para um layout como este (tamanho fixo e centralizado na visão dos pais), seria mais simples usar a máscara de redimensionamento automático e deixar o sistema traduzir a máscara em restrições:

 var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100)) new_view.backgroundColor = UIColor.redColor(); view.addSubview(new_view); // This is the default setting but be explicit anyway... new_view.translatesAutoresizingMaskIntoConstraints = true new_view.autoresizingMask = [ .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleLeftMargin, .FlexibleRightMargin ] new_view.center = CGPointMake(view.bounds.midX, view.bounds.midY) 

Observe que usar o redimensionamento automático é perfeitamente legítimo mesmo quando você também está usando o autolayout. (O UIKit ainda usa o redimensionamento automático em muitos lugares internamente.) O problema é que é difícil aplicar restrições adicionais a uma visão que está usando o redimensionamento automático.

O layout automático é realizado aplicando restrições nas imagens. Use NSLayoutConstraint. É possível implementar um design ideal e bonito em todos os dispositivos. Por favor, tente o código abaixo.

 import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let myImageView:UIImageView = UIImageView() myImageView.backgroundColor = UIColor.red myImageView.image = UIImage(named:"sample_dog")! myImageView.translatesAutoresizingMaskIntoConstraints = false myImageView.layer.borderColor = UIColor.red.cgColor myImageView.layer.borderWidth = 10 self.view.addSubview(myImageView) view.removeConstraints(view.constraints) view.addConstraint(NSLayoutConstraint( item: myImageView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant:100) ) view.addConstraint(NSLayoutConstraint( item: myImageView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant:0) ) view.addConstraint(NSLayoutConstraint( item: myImageView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 0.5, constant:40)) view.addConstraint(NSLayoutConstraint( item: myImageView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 0.5, constant:40)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } 

insira a descrição da imagem aqui insira a descrição da imagem aqui

é um pouco diferente no xcode 7.3.1. é isso que eu invento

  // creating the view let newView = UIView() newView.backgroundColor = UIColor.redColor() newView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(newView) // creating the constraint // attribute and relation cannot be set directyl you need to create a cariable of them let layout11 = NSLayoutAttribute.CenterX let layout21 = NSLayoutRelation.Equal let layout31 = NSLayoutAttribute.CenterY let layout41 = NSLayoutAttribute.Width let layout51 = NSLayoutAttribute.Height let layout61 = NSLayoutAttribute.NotAnAttribute // defining all the constraint let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: layout11, relatedBy: layout21, toItem: view, attribute: layout11, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: newView, attribute: layout31, relatedBy: layout21, toItem: view, attribute: layout31, multiplier: 1, constant: 0) let widthConstraint = NSLayoutConstraint(item: newView, attribute: layout41, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100) let heightConstraint = NSLayoutConstraint(item: newView, attribute: layout51, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100) // adding all the constraint NSLayoutConstraint.activateConstraints([horizontalConstraint,verticalConstraint,widthConstraint,heightConstraint]) 

Atualizado para o Swift 3

 import UIKit class ViewController: UIViewController { let redView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .red return view }() override func viewDidLoad() { super.viewDidLoad() setupViews() setupAutoLayout() } func setupViews() { view.backgroundColor = .white view.addSubview(redView) } func setupAutoLayout() { // Available from iOS 9 commonly known as Anchoring System for AutoLayout... redView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true redView.heightAnchor.constraint(equalToConstant: 300).isActive = true // You can also modified above last two lines as follows by commenting above & uncommenting below lines... // redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true // redView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } } 

insira a descrição da imagem aqui

Tipo de restrições

  /* // regular use 1.leftAnchor 2.rightAnchor 3.topAnchor // intermediate use 4.widthAnchor 5.heightAnchor 6.bottomAnchor 7.centerXAnchor 8.centerYAnchor // rare use 9.leadingAnchor 10.trailingAnchor etc. (note: very project to project) */ 
  var xCenterConstraint : NSLayoutConstraint! var yCenterConstraint: NSLayoutConstraint! xCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterX, relatedBy: .Equal, toItem: (Your view NAme), attribute: .CenterX, multiplier: 1, constant: 0) self.view.addConstraint(xCenterConstraint) yCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterY, relatedBy: .Equal, toItem: (Your view Name), attribute: .CenterY, multiplier: 1, constant: 0) self.view.addConstraint(yCenterConstraint) 

Esta é uma maneira de adicionar restrições programaticamente

 override func viewDidLoad() { super.viewDidLoad() let myLabel = UILabel() myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor) self.view.addSubview(myLabel) let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10) let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10) let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50) NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\]) } extension UILabel { func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){ label.translatesAutoresizingMaskIntoConstraints = false label.text = text label.font = font label.textColor = textColor label.textAlignment = textAlignment label.numberOfLines = numberOfLines label.layer.borderWidth = borderWidth label.layer.borderColor = UIColor.red.cgColor } } 

insira a descrição da imagem aqui

Restrições para várias visualizações no playground.

rápido 3+

  var yellowView: UIView! var redView: UIView! override func loadView() { // UI let view = UIView() view.backgroundColor = .white yellowView = UIView() yellowView.backgroundColor = .yellow view.addSubview(yellowView) redView = UIView() redView.backgroundColor = .red view.addSubview(redView) // Layout redView.translatesAutoresizingMaskIntoConstraints = false yellowView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), yellowView.widthAnchor.constraint(equalToConstant: 80), yellowView.heightAnchor.constraint(equalToConstant: 80), redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), redView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -20), redView.widthAnchor.constraint(equalToConstant: 80), redView.heightAnchor.constraint(equalToConstant: 80) ]) self.view = view } 

In my opinion xcode playground is the best place for learning adding constraints programmatically.

Playground image

If you find the above to be ugly. You should consider using a DSL for constraints. Such as SnapKit Makes constraint API much more user-friendly

 view.snp.makeConstraints { make in make.edges.equalToSuperview() } 

You are adding all defined constraints to self.view which is wrong, as width and height constraint should be added to your newView .

Also, as I understand you want to set constant width and height 100:100. In this case you should change your code to:

 var constW = NSLayoutConstraint(item: newView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100) newView.addConstraint(constW) var constH = NSLayoutConstraint(item: newView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100) newView.addConstraint(constH) 

I created these views in given fig. using Autolayout programmatically. You will get a deep understanding of constraints and how do they should be applied properly.

You can refer it here “Introduction to Autolayout”

insira a descrição da imagem aqui

Intereting Posts