【发布时间】:2016-02-20 21:19:29
【问题描述】:
我正在使用 Swift 为移动应用程序类制作一个简单的温度转换器。 我们有点轻而易举,所以我没有太多的经验。我在编译它时遇到了很多问题,但最终我得到了一切都很好而且整洁,没有任何警告或错误,而且我对我的 MVC 样式代码感到满意。唯一的问题是,当我输入一个临时值并单击“转换”按钮时,我的日志检查点证明我得到了正确的双精度值进行转换,并且我将其转换为字符串,但是当我尝试更改 outputText 标签时,我得到致命错误:在展开可选值时意外发现 nil。我希望这是一件非常简单的事情,第二双眼睛可以捕捉到。 我的应用看起来像这样...
我的 ViewController 是...
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var tempInput: UITextField!
@IBOutlet weak var tempOutput: UILabel!
@IBOutlet weak var convertMethod: UISwitch!
override func viewDidLoad()
{
print("view load confirmed");
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 convert(sender: AnyObject!)
{
print ("button press confirmed");
let t = Double(tempInput.text!)
let m = convertMethod.on
let result = convertModel(temp:t!,method:m)
print("result has been set to object variable created as stated above");
let afterConvert = result.convertTemp()
print("the convertTemp method was called and the result was stored as the double: \(afterConvert)");
let finalForm = String(afterConvert)
print("converted the double into the string: \(finalForm)");
tempOutput.text = finalForm
//^^^^^^^ this is the line that fails
}
}
我的 convertModel 类(我知道,该类应该大写,当我注意到并尝试更改它时,它破坏了一切)是......
import Foundation
class convertModel
{
var temp:Double?
var method:Bool?
init(temp:Double,method:Bool)
{
self.temp = temp
self.method = method
print("object of type convertModel created with \(temp) as temp and \(method) as method");
}
func convertTemp()->Double
{
print("convertTemp method entered");
if method == true
{
print("if conditional entered");
print("conversion completed, exiting convertTemp method");
return (temp! * (9/5) + 32)
}
else
{
print("else conditional entered");
print("conversion completed, exiting convertTemp method");
return (temp! - 32) * (5/9)
}
}
}
非常感谢任何帮助。但请记住,这是非常 Swift 101,因此任何过于复杂的解决方案都无济于事。谢谢。
【问题讨论】:
-
你连接故事板的插座了吗?你检查过你的方法/文本字段没有返回 nil 吗?
-
我的第一个猜测是你的按钮没有连接。有 2 种常用方法可以测试您的代码是否按预期工作:断点和打印语句。只需将一些打印语句添加到您的代码中,然后查看它们何时停止发生。我建议您的第一个 print() 位于按下按钮时调用的函数的开头
-
显然连接不正确。我放了一些打印语句,我在 viewDidLoad 上看到了那个,但是当我单击按钮时什么也没有。有没有办法在事后将它们连接起来?我尝试创建另一个按钮来连接我学习的方式,而 click 方法中唯一的东西是打印语句,它使应用程序崩溃而没有错误消息,只显示打印语句行并显示线程 1:断点 3.1
-
在打开并排编辑器和 ctrl 从按钮拖动到操作方法之后连接它们。还要确保您在所有内容上都只有您想要的参考。
-
是的,那做了一些事情,现在我的 click 方法和 ConvertModel 构造函数中的 print 语句都打印了,但是之后线程在某处中断。无论如何,我将不得不进一步研究,至少我知道按钮可以工作,谢谢!
标签: swift model-view-controller uibutton xcode7-beta6