问题
我试图完全理解完全以编程方式构建Swift应用程序,但我已经挂断了布局锚点。我有一个tableview,如果选择了一行,它会将一个新的viewcontroller推送到视图中。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentCell = tableView.cellForRow(at: indexPath)! as! CoinCell
if let coin = currentCell.coin {
let newViewController = CoinViewController(coin)
self.navigationController?.pushViewController(newViewController, animated: true)
}
tableView.deselectRow(at: indexPath, animated: true)
}
下面是我正在推送的viewcontroller的代码。我能够在调试时看到名称标签有文字,但我似乎无法在视图中显示标签。
var coin: Coin? {
didSet {
nameLabel.text = coin?.name
}
}
init(_ coin: Coin) {
super.init(nibName: nil, bundle: nil)
self.coin = coin
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(nameLabel)
view.addSubview(testLabel)
setupView()
}
let nameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let testLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "TEST"
return label
}()
func setupView() {
nameLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
nameLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
nameLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
nameLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
我还是初学者,所以我不确定实际调试此类问题的最佳方法。谢谢你的帮助。
答案 0 :(得分:1)
由于您正在确保控制器通过initializer
接收数据(或非可选数据),因此您应该将property observer
(didSet)替换为一个简单的属性。
let coin: Coin
init(_ coin: Coin) {
self.coin = coin
super.init(nibName: nil, bundle: nil)
}
// now in viewDidLoad() you can set the text of your label i.e namelabel.text = self.coin.something
答案 1 :(得分:1)
您尝试在属性观察器中设置文本nameLabel
:
var coin: Coin? {
didSet {
nameLabel.text = coin?.name
}
}
但didSet
将从初始化程序中调用,因此标签将保持为空。
在iOS(Cocoa Touch)中,您应该在viewDidLoad
之后/之内填充您的观看次数(或viewDidAppear
)或 - 在您的情况下 - 在setupView
中填写您的观点:
func setupView() {
nameLabel.text = coin?.name
// ...
}