我有一个UISwitch
,我想在我编写的函数中控制一个布尔值。我查看了UISwitch
类型参考,它列出了开关的开/关状态的属性为on
。我试着在一个动作中使用这个:
@IBAction func switchValueChanged(sender: UISwitch) {
if acsessabilitySwitch.on {
//accessibilitySwitch is the UISwitch in question
println("It's True!")
advice.isInProduction = Bool (true)
// isInProduction is a attribute of a class
} else {
println("It's False!")
advice.isInProduction = Bool (false)
}
但当我运行它并按下开关时,它崩溃了,没有打印任何东西。
编辑:这是我的ViewController和我的自定义类文件:
BuyingAdviceModel.swift:
import Foundation
class videoGameModel{
var price : Double
var isInProduction : Bool
var adviceGiven: String?
init (isInProduction : Bool, price: Double){
self.price = price
self.isInProduction = isInProduction
}
func giveAdvice (price:Double, isInProduction:Bool)->(adviceGiven:String){
if price >= 199.99 {
var adviceGiven = "Nope, that's too expensive!"
return adviceGiven
} else if price <= 99.99{
if isInProduction == true {
var adviceGiven = ("Buy it at GameStop!")
return adviceGiven
} else {
var adviceGiven = ("Go look online!")
return adviceGiven
}
} else {
var adviceGiven = ("Are you sure you put the info in correctly?")
return adviceGiven
}
}
}
ViewController.swift:
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet var priceTextField: UITextField
@IBAction func adviceButtonTapped(sender: AnyObject) {
let adviceOutputed = advice.adviceGiven!
adviceLabel.text=adviceOutputed
}
@IBAction func viewTapped(sender: AnyObject) {
priceTextField.resignFirstResponder()
}
@IBOutlet var acsessabilitySwitch: UISwitch
@IBOutlet var adviceLabel: UILabel
@IBAction func switchValueChanged (sender: UISwitch) {
advice.isInProduction = sender.on
println ("It's " + advice.isInProduction.description + "!")
}
var advice = videoGameModel (isInProduction: true,price: 0.00)
func refreshUI(){
priceTextField.text = String(advice.price)
adviceLabel.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
发布于 2014-07-13 00:46:46
简洁性,甚至简洁性,在编码风格中很重要。试试这个:
@IBAction func switchValueChanged (sender: UISwitch) {
advice.isInProduction = sender.on
print ("It's \(advice.isInProduction)!")
}
在您的原始代码中,您很可能因为acsessabilitySwitch
或advice
未绑定(值为nil
)而崩溃。
更新-用print
替换了println
发布于 2017-05-04 20:04:18
对于swift 3
@IBAction func switchValueChanged(_ sender: UISwitch) {
print(sender.isOn)
}
发布于 2016-05-11 21:27:20
从对象库拖放UISwitch -
@IBOutlet-
@IBOutlet weak var myswitch: UISwitch!
@IBAction-
@IBAction func onAllAccessory(sender: UISwitch) {
if myswitch.on == true{
onCall()
}
if myswitch.on == false{
offCall()
}
}
你的功能-
func onCall(){
print("On is calling")
}
func offCall(){
print("Off is calling")
}
https://stackoverflow.com/questions/24714921
复制相似问题