我正在做一个游戏,当按下按钮两次时,它将转移到另一个视图控制器。现在,用户反应时间在视图控制器a中计时。我希望为视图控制器b设置时间,而在视图控制器b中的时间要减去1。当两次按下按钮时,视图控制器会更改,但文本不会被传输。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var labelx: UILabel!
    @IBOutlet var startx: UIButton!
    @IBOutlet var pressSoccerBall: UIButton!
    var level = 0
    var timer: Timer?
    var isRunning: Bool {
        get {
            return timer != nil
        }
    }
    var counter = 0.0

    override func viewDidLoad() {
        super.viewDidLoad()
        labelx.text = String(format: "%.1f", counter)
        startx.isEnabled = true
    }

    @IBAction func startTimer(_ sender: Any) {
        if isRunning {
            return
        }
        refreshTimer()
    }

    @IBAction func PressSoccerBall(_ sender: Any) {
        level += 1
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let DestViewController : winViewController = segue.destination as!      winViewController
        DestViewController.LebelText = labelx.text!
    }

    func refreshTimer() {

        if let timer: Timer = timer {
            timer.invalidate()
        }
        timer = Timer.scheduledTimer(timeInterval: 0.1,target: self,selector: #selector(updateTimer),userInfo: nil, repeats: true)
        startx.isEnabled = false
    }

    func updateTimer() {
        counter += 0.1
        labelx.text = String(format: "%.1f", counter)
        if counter < 9.9 && level == 2 {
            let nextc =   self.storyboard?.instantiateViewController(withIdentifier: "winViewController") as? winViewController
            self.present(nextc!, animated: true, completion: nil)
        }
    }
}




视图控制器B

import UIKit

class winViewController: UIViewController {

    @IBOutlet var winningLabel: UILabel!
    public var LebelText: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        steve()
    }

    func steve(){

        guard let unwrapedText = self.LebelText else {
            return
        }
        if let myInt = Double(unwrapedText){
            let  myInt = myInt - 1
            self.winningLabel.text = String(myInt)

        } else {
            return
        }
    }

}

最佳答案

您没有使用segues。您正在创建winViewController,然后调用present来显示它。因此,将永远不会调用prepareForSegue

只需在显示前在LebelText上设置nextc属性即可:

func updateTimer() {
    counter += 0.1
    labelx.text = String(format: "%.1f", counter)
    if counter < 9.9 && level == 2 {
        if let nextc = self.storyboard?.instantiateViewController(withIdentifier: "winViewController") as? winViewController {
            nextc.LebelText = labelx.text
            self.present(nextc, animated: true, completion: nil)
        }
    }
}

关于ios - Segue未转移到(Swift 3),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41528296/

10-11 02:06