swift - 不同 ViewController 上的 Xcode Swift 导航栏

标签 swift xcode label navigationbar

当 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/

相关文章:

swift - 为什么关键字 "weak"只能应用于class和class-bound协议(protocol)类型

scala - 使用 Scala 转换 LabeledPoint 中 Vector 的 RDD - Apache Spark 中的 MLLib

ios - 如何在禁用用户交互的 UITableViewController 顶部添加模态视图

swift - 如何将 CMRotationmatrix 转到初始位置

swift - SwiftUI 中的几何阅读器是什么?

ios - SiriKit 和 CNContactStore

xcode - 调试区域中显示的信息过多 - Xcode 8

xcode - 内购 : Restoring a purchase no longer for sale

c# - 如何在 NX Open C# 中标记一行?

conditional-statements - gnuplot,如何仅标记某些点?