Dodałem UIView
, używając IB do kontrolera widoku. Nazwijmy to redView
.Dodawanie podglądu podrzędnego i programowe umieszczanie go w ograniczeniach
Wtedy mam przypięte jego wszystkie cztery boki przy użyciu układu automatycznego ograniczenia w kodzie i po uruchomieniu go, wygląda to tak, jak oczekiwano.
Teraz chcę dodać UILabel
z tym poglądem programowo i umieść go w centrum przy użyciu automatycznego układu ograniczeń.
Poniżej znajduje się kod, który mam do tej pory.
import UIKit
class ViewController: UIViewController {
@IBOutlet private var redView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
redView.setTranslatesAutoresizingMaskIntoConstraints(false)
let leadingConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: redView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: redView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: redView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
let label = UILabel()
label.text = "Auto Layout Exercise"
redView.addSubview(label)
let xCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: redView, attribute: .CenterX, multiplier: 1, constant: 0)
let yCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: redView, attribute: .CenterY, multiplier: 1, constant: 0)
let leadingConstraint1 = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: redView, attribute: .Leading, multiplier: 1, constant: 20)
let trailingConstraint1 = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: redView, attribute: .Trailing, multiplier: 1, constant: -20)
redView.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])
}
}
Problem polega na tym, że etykieta nie pojawia się na redView
. Czy ktoś może mi powiedzieć, czego tu brakuje?
Dziękuję.
I rzeczywiście powinien być wyświetlany komunikat w konsoli w tym względzie. – matt
I dziękuję niebiosom za tę wiadomość w konsoli, ponieważ jest prawie pewne, że za każdym razem będę zapominał ten wiersz kodu. :) – matt
Tak, to była przyczyna. Kiedyś testowałem z linią 'redView'' 'setTranslatesAutoresizingMaskIntoConstraints', ale nie wpłynęło to na widok, więc pomyślałem, że ta linia nie jest obowiązkowa. Sądzę, że jest to widok, który tworzysz programowo. Dzięki. – Isuru