我已经成功更新了文本字段的值,现在我正在尝试添加第二个步进器,但应用程序现在崩溃了。
@IBOutlet weak var propertyTypeField: UITextField!
@IBOutlet weak var insuranceTypeField: UITextField!
@IBOutlet weak var bedroomField: UITextField!
@IBOutlet weak var bathroomField: UITextField!
@IBOutlet weak var doYouOwnPropertyField: UITextField!
@IBOutlet weak var propertyYearField: UITextField!
@IBOutlet weak var bathroomStepper: UIStepper!
@IBOutlet weak var bedroomStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 0xE1/255, green: 0xE1/255, blue: 0xE1/255, alpha: 1.0)
//Bedroom stepper setup
bedroomField.text = "\(Int(bedroomStepper.value))"
bedroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
//Bathroom stepper setup
bathroomField.text = "\(Int(bathroomStepper.value))"
bathroomStepper.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func viewTapped(sender : AnyObject) {
propertyTypeField.resignFirstResponder()
insuranceTypeField.resignFirstResponder()
bedroomField.resignFirstResponder()
bathroomField.resignFirstResponder()
doYouOwnPropertyField.resignFirstResponder()
propertyYearField.resignFirstResponder()
}
func stepperValueDidChange(stepper: UIStepper) {
let bedroomStepperMapping: [UIStepper: UITextField] = [bedroomStepper: bedroomField]
if !(bedroomField.text == ""){
bedroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
let bathroomStepperMapping: [UIStepper: UITextField] = [bathroomStepper: bathroomField]
if !(bathroomField.text == ""){
bathroomStepperMapping[stepper]!.text = "\(Int(stepper.value))"}
}
这是我正在使用的整个代码。
我得到的错误是
致命错误:在解包可选值时意外发现nil
希望有人可以提供帮助。
由于
答案 0 :(得分:0)
通过使用!
bedroomStepperMapping[stepper]!.text
告诉编译器,那里会有一个值。因为没有人显然你得到错误。在打开它之前检查值是否为零
要检查行中是否为nil
if !(bedroomField.text == ""){
//Ok to unwrap object
}
答案 1 :(得分:0)
如果您正在使用可选值,那么首先检查值是否存在,如果不存在那么必须不是b null所以这样做
if let bedFeild = Int(stepper.value) {
bedroomStepperMapping[stepper].text = bedFeild
}
现在,如果值存在则不会崩溃,那么将为其分配值,否则不会发生任何崩溃
答案 2 :(得分:-1)
func stepperValueDidChange(stepper: UIStepper) {
if bedroomStepper == stepper{
bedroomField.text = "\(Int(stepper.value))"}
if bathroomStepper == stepper{
bathroomField.text = "\(Int(stepper.value))"}
}
}