简体   繁体   English

将值传递给另一个类并在该视图控制器上显示

[英]Passing a value to another class and displaying it on that view controller

I have two .swift classes. 我有两个.swift类。 Test.swift and Start.swift . Test.swiftStart.swift

Start.swift has a func called outputPercentage . Start.swift有一个名为outputPercentage的函数。 See below. 见下文。

var startClass = StartView()


class StartView: UIViewController {

    @IBOutlet var testProg: UILabel!

    override func viewDidLoad() {
            super.viewDidLoad()
            testClass.sendpct()
        }

    func outputPercentage(pct: Int32) {
       let pctTxt = String(pct)
       print("Test Progress: ", pctTxt as Any)
       testProg.text = "Test" //pctTxt! + " / 100"
    }
}

testProg is a UILabel . testProg是一个UILabel

The func below is in Test.swift and passes an Int32 value back to the function above in Start.swift , like so: 下面的函数位于Test.swift中 ,并将Int32值传递回上述Start.swift中的函数,如下所示:

var testClass = TestView()

class TestView {

  func sendpct() {
     var percentComplete : Int32 = 0;
     startClass.outputPercentage(pct: percentComplete)
  }

}

The line below gives me an " Unexpected optional nil " error. 下面的行给了我一个“ Unexpected optional nil ”错误。

testProg.text = pct_txt! + " / 100"

The UILabel is all set up correctly as I can set it elsewhere in the class, this error only occurs when the value has been passed from the other class. 可以正确设置UILabel ,因为我可以在该类的其他地方设置它,仅当从另一个类传递了值时才会发生此错误。

How do I correctly output the value to my UILabel ? 如何正确将值输出到UILabel

It is better to use Delegate for your case. 最好为您的案例使用Delegate。

In Start.swift Start.swift中

import UIKit

protocol StartDelegate: class {
    func outputPercentage(pct: Int32)
}

class StartView: UIViewController, StartDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
        var test = Test()
        test.startDelegate = self
        test.sendpct()
    }

    // MARK: - Delegate Methods

    func outputPercentage(pct: Int32) {
        print(pct)
    }

}

In Test.swift Test.swift中

class Test {

    weak var startDelegate: StartDelegate?

    func sendpct() {
        if let startDelegate = startDelegate {
            var percentComplete : Int32 = 0;
            startDelegate.outputPercentage(pct: percentComplete)
        }
    }

}

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM