将UILabel添加到ViewController时,它显示正常,但是一旦我使用单独的UIView,该控制器就什么也不显示。 ViewController是从TableViewController.didSelectRowAt
推送的ViewController在didSelectRowAt中被调用
let labelViewController = TempViewController()
navigationController?.pushViewController(labelViewController, animated: true)
方案1:仅ViewController-显示蓝屏,其文本位于屏幕y中心,如预期的那样
class TempViewController: UIViewController {
var tempView: UILabel = {
let label = UILabel()
label.text = "Please enter your email address"
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.blue
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
navigationItem.title = "Temp"
edgesForExtendedLayout = []
view.addSubview(tempView)
tempView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tempView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tempView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tempView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
方案2:ViewController和视图-显示红色屏幕,没有文本,没有蓝色
class TempViewController: UIViewController {
var tempView = TempView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
navigationItem.title = "Temp"
edgesForExtendedLayout = []
view.addSubview(tempView)
tempView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tempView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tempView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tempView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
}
class TempView: UIView {
var tempView: UILabel = {
let label = UILabel()
label.text = "Please enter your email address"
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.blue
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setView()
}
private func setView() {
addSubviews()
setLayout()
}
private func addSubviews() {
addSubview(tempView)
}
private func setLayout() {
tempView.topAnchor.constraint(equalTo: topAnchor).isActive = true
tempView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
tempView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
tempView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
我希望两种情况都能产生相同的结果?但是方案2不显示视图吗?
感谢您的帮助
答案 0 :(得分:0)
您的视图未显示,因为它过于受限。
您还需要在translatesAutoresizingMaskIntoConstraints = false
中为tempView
设置viewDidLoad()
:
view.addSubview(tempView)
tempView.translatesAutoresizingMaskIntoConstraints = false
tempView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tempView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tempView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tempView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true