I am trying to call a function from TheTimer class from my MainClass class. However, in the TheTimer class there is a required init, and when I try and call the Start function from the TheTimer class (I call it from the MainClass class) it throws the error: Missing argument for parameter 'coder' in call
The TheTimer class is responsible for a UIView that is part of my storyboard.
TheTimer:
class TheTimer: UIView {
var timeLabel: UILabel
required init?(coder aDecoder: NSCoder) {
timeLabel = UILabel()
super.init(coder: aDecoder)
let viewWidth = self.frame.size.width
let viewHeight = self.frame.size.height
timeLabel.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
timeLabel.text = "0"
timeLabel.font = UIFont(name: "Arial", size: 45)
timeLabel.textAlignment = NSTextAlignment.center
self.addSubview(timeLabel)
}
//MARK: Properties
var time: Double = 0.000
var timer = Timer()
func Start() {
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(countUp), userInfo: nil, repeats: true)
}
@objc func countUp() {
time += 0.001
}
MainClass Class
import UIKit
class MainClass: UIViewController {
//MARK: Properties
@IBOutlet weak var answerLabel: UILabel!
//MARK: Go
@IBAction func startAll(_ sender: UIButton) {
TheTimer().Start() //Throws error 'Missing argument for parameter 'coder' in call'
}
}
In your MainClass
class, create a property for your TheTimer
view, after that connect your TheTimer
in story board with this IBOutlet
. Finally, call theTimer.Start()
instead of TheTimer().Start()
import UIKit
class MainClass: UIViewController {
//MARK: Properties
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var theTimer: TheTimer!
//MARK: Go
@IBAction func startAll(_ sender: UIButton) {
theTimer.Start() // It will work fine
}