如何设置标签,以便在按下按钮时,它将更改标签上显示的值

时间:2017-03-21 12:59:15

标签: ios swift xcode uibutton uilabel

如何设置标签,以便在按下按钮时,它将更改标签上显示的值,并将其设置为每按一次按钮,它们都将添加到之前的数字按下 - 是否可以在同一个视图控制器上设置2个视图场景?

    @IBOutlet weak var creditLabel: UILabel!

    var savedNum:Int = "Credits: /0"

    var Money : Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    @IBAction func oneDollar(_ sender: Any) {
        let oneDollar = 1
    }

    @IBAction func fiveDollars(_ sender: Any) {
        let fiveDollars = 5
    }

    @IBAction func tenDollars(_ sender: Any) {
        let tenDollars = 10
    }
    @IBAction func twentyDollars(_ sender: Any) {
        let twentyDollars = 20
    }
    @IBAction func fiftyDollars(_ sender: Any) {
        let fiftyDollars = 50
    }
    @IBAction func oneHundredDollars(_ sender: Any) {
        let oneHundredDollars = 110
    }

}

2 个答案:

答案 0 :(得分:2)

我认为你要做的就是这样......

class ViewController: UIViewController {

    @IBOutlet weak var creditLabel: UILabel!

    var credit = 0 {
       didSet {
           creditLabel.text = "Credit: $\(credit)"
       }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        credit = 0
    }


    @IBAction func oneDollar(_ sender: Any) {
        credit += 1
    }

    @IBAction func fiveDollars(_ sender: Any) {
        credit += 5
    }

    // etc
}

答案 1 :(得分:-1)

你的标签是否已连接到你的UIViewController?相应的行动怎么样?您是否将相同的操作连接到同一个按钮?需要更多信息来帮助解决被抛出的错误。