通过带有加法和减法计数器的视图控制器传递整数值[重复]

Posted

技术标签:

【中文标题】通过带有加法和减法计数器的视图控制器传递整数值[重复]【英文标题】:Passing an integer value through view controllers with an addition and subtraction counter [duplicate] 【发布时间】:2020-07-21 21:44:15 【问题描述】:

我正在开发一款 Magic the Gathering Counter 应用程序。对于我的应用,我想点击twentyLife()thirtyLife()fourtyLife() 来更改另一个视图控制器(即FifthViewController)中的变量值。

第二个视图控制器代码:

import UIKit


class SecondViewController: UIViewController 
    var vcFive = FifthViewController()

override func viewDidLoad() 
    super.viewDidLoad()

    // Do any additional setup after loading the view.

@IBAction func twentyLife() 
    vcFive.lifePoints.text = String(20)
    

@IBAction func thirtyLife() 
    vcFive.lifePoints.text = String(20)
    


@IBAction func fortyLife() 
    vcFive.lifePoints.text = String(20)

我尝试调用 FifthViewController 作为变量来更改我的生活点文本,但它不起作用。

这是我的第五个视图控制器的代码:

import UIKit

class FifthViewController: UIViewController 
    @IBOutlet weak var lifePoints: UILabel!
    var counter = 0
    

override func viewDidLoad() 
    super.viewDidLoad()

    // Do any additional setup after loading the view.


@IBAction func lifeUp() 

    counter += 1
    lifePoints.text = String(counter)


@IBAction func lifeDown() 
    counter -= 1
    lifePoints.text = String(counter)

任何帮助将不胜感激。这是我一直在尝试从头开始开发的第一个应用程序

【问题讨论】:

【参考方案1】:

您应该在SecondViewController 上创建FifthViewController 的实例,并在FifthViewController 上创建一个变量,您可以在其中保存传递的数据。像这样:

SecondViewController

import UIKit


class SecondViewController: UIViewController 
    
    let fifthVC = self.storyboard?.instantiateViewController(withIdentifier: "fifthVC") as? FifthViewController

    override func viewDidLoad() 
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    

    @IBAction func twentyLife() 
        fifthVC.lifePointsInt = 20

    

    @IBAction func thirtyLife() 
        fifthVC.lifePointsInt = 30

    

    @IBAction func fortyLife() 
        fifthVC.lifePointsInt = 50
    

FifthViewController

import UIKit

class FifthViewController: UIViewController 
    var lifePointsInt = Int()
    @IBOutlet weak var lifePoints: UILabel!


    override func viewDidLoad() 
        super.viewDidLoad()

        lifePoints.text = "\(lifePointsInt)"
    

    @IBAction func lifeUp() 
        lifePoints.text = "\(lifePointsInt + 1)"
    

    @IBAction func lifeDown() 
        lifePoints.text = "\(lifePointsInt - 1)"
    

记得在你的 FifthViewController 的情节提要中输入你的情节提要 ID 为 "fifthVC" 如果在你的 SecondViewController 中选择你的生命计数后,你的传递到你的 FifthViewController,你可以在末尾添加 self.navigationController?.pushViewController(fifthVC!, animated: true)每个功能。

【讨论】:

谢谢。我现在在我的第二个视图控制器上收到此错误。代码:'(SecondViewController) -> () -> SecondViewController' 类型的值没有成员'storyboard' 那是在特定的代码行上吗?故事板上的 SecondViewController 是否与 Swift 文件相关联?

以上是关于通过带有加法和减法计数器的视图控制器传递整数值[重复]的主要内容,如果未能解决你的问题,请参考以下文章

JUC工具包之加法减法计数器信号量

计算机的算数运算 知识梳理

Shell运算

通过DataFrame查询计数查询时如何获取整数值?

Excel 2007减法得数变成了5E-05怎么办?

常用的垃圾回收算法