[英]how to init() a swift view controller properly?
I'm attempting to initialize this ViewController class. 我正在尝试初始化此ViewController类。 I am not using the MVC design strategy so ignore the bad conventions used (if any).
我没有使用MVC设计策略,所以忽略使用的不良约定(如果有的话)。
How do I initialize this class properly? 如何正确初始化此类?
Error: 'required' initializer 'init(coder:)' must be provided by subclass of 'UIViewController' 错误:'required'初始化程序'init(coder :)'必须由'UIViewController'的子类提供
Context: This is a calculator app that when any of the buttons are pressed. 上下文:这是一个计算器应用程序,按下任何按钮时。 It will go find the senders title and simply put if one of the three vars are nil, it will store it in that optional.
它将找到发件人的标题,并简单地说,如果三个变量中的一个是零,它将存储在该可选项中。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var answerLabel: UILabel!
//global vars for all funcs
var selection1: Int? {
didSet { answerLabel.text = String(selection1!) }
}
var selection2: String? {
didSet { answerLabel.text = selection2! }
}
var selection3: Int? {
didSet { answerLabel.text = String(selection3!) }
}
var answer: Int {
didSet { answerLabel.text = String(answer) }
}
init() {
}
@IBAction func touchButton(_ sender: UIButton) {
if selection1 == nil {
selection1 = Int(sender.currentTitle!)
print("Selection set in first pos.")
} else if selection2 == nil {
selection2 = sender.currentTitle
} else if selection3 == nil {
selection3 = Int(sender.currentTitle!)
} else {
calculate(firstNum: selection1!, operation: selection2!, secondNum: selection3!)
}
}
func calculate(firstNum: Int, operation: String, secondNum: Int) {
switch operation {
case "+":
answer = firstNum + secondNum
case "-":
answer = firstNum - secondNum
case "x":
answer = firstNum * secondNum
case "/":
answer = firstNum / secondNum
default:
answerLabel.text = "Something went wrong!"
}
}
}
Your controller is being instantiated from the storyboard. 您的控制器正在从故事板中实例化。 A safe place to configure initial views is during the controller's call to
viewDidLoad
, ie: 配置初始视图的安全位置是在控制器调用
viewDidLoad
,即:
override func viewDidLoad() {
super.viewDidLoad()
// configure your views and subviews here
}
Initialization depends on a couple of condition. 初始化取决于几个条件。
init
and your VC will have default initializer. init
,VC将具有默认初始化程序。 Make sure either all of your properties have default value or they are optional. xib
or just creating view programmatically you can have custom convenience initializer where you pass some extra data this way. xib
或只是以编程方式创建视图,则可以使用自定义便利初始化程序以这种方式传递一些额外数据。 class MyViewController: ViewController {
var answer: Int
convenience init(answer: Int) {
self.init()
self.answer = answer
// Do other setup
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.