当 FirstViewController 的 View 第一次打开时,导航栏中会出现一个标签。标签显示的数字应该可以更改。如果我单击 FirstViewController 上的按钮,SecondViewController 的 View 将显示在导航栏中,FirstViewController 的标签仍然可见。当我通过单击 SecondViewController 中的按钮更改标签中写入的数字时,只有当我返回到 FirstViewController 的 View 时,标签的数字才会发生变化。这是因为我在 ViewDidLoad String 循环中更新了标题。 现在我的问题是: 尽管标签是在 FirstViewController 的代码中定义的,但我希望在单击 SecondViewController 中的按钮时更改标签的编号。标签上的数字表示金额。
这是 FirstViewController 的代码:
var moneyLabel: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationLabel()
let newMoney:String = String(format: "%f", money)
updateTitle(title: "\(newMoney)")
}
func updateTitle(title: String) {
if let myTitleView = self.moneyLabel {
myTitleView.text = title
}
}
func setupNavigationLabel() {
let navigationBar = self.navigationController?.navigationBar
let moneyFrame = CGRect(x: 300, y: 0, width:
(navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)
moneyLabel = UILabel(frame: moneyFrame)
moneyLabel?.text = "\(money)"
navigationBar?.addSubview(moneyLabel!)
}
最佳答案
看来您的问题出在第二个 ViewController
上,但您没有共享任何代码!使用以下方法来实现您的目标。
class secondViewControler:UIViewController{
var money:Int
var moneyLabel:UILAbel?
override func viewDidLoad(){
self.money= //pass the amount, i dont know which way you use to store and retrieve the amount
moneyLabel.text="\(money)"
}
@IBAction updateMoney(){
//get the amount from the textfield say the output is X
money=X
moneyLabel.text="\(money)"
}
}
关于swift - 不同 ViewController 上的 Xcode Swift 导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50727895/