在我的 View Controller 中:
class FoodAddViewController: UIViewController, UIPickerViewDataSource, UITextFieldDelegate, UIPickerViewDelegate {
let TAG = "FoodAddViewController"
// Retreive the managedObjectContext from AppDelegate
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
@IBOutlet weak var foodName: UITextField!
@IBOutlet weak var foodPortion: UITextField!
@IBOutlet weak var foodCalories: UITextField!
@IBOutlet weak var foodUnit: UILabel!
@IBOutlet weak var unitPicker: UIPickerView!
@IBOutlet weak var unitPickerViewContainer: UIVisualEffectView!
/*
unrelated code has been ommited
*/
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
func validateTextField(textField: UITextField) -> Bool{
let correctColor = UIColor.redColor().CGColor, normalColor = UIColor.blackColor().CGColor
var correct = true
if textField == foodPortion || textField == foodCalories{
if !Misc.isInteger(textField.text!){
correct = false
}
}
if textField.text!.isEmpty {
correct = false
}
textField.layer.borderColor = correct ? normalColor : correctColor
return correct
}
}
我有几个文本字段,在我的 validateTextField 中可以一次验证一个,并且我希望我的 validateAllTextFields 能够通过逐一检查来验证给定的文本字段列表,如果未给出列表,我想要检查包含所有三个文本字段的给定默认列表。
我想象的代码是这样的:
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
但是 Xcode 返回错误:
instance member cannot be used on type viewcontroller
原因是什么以及如何解决?
最佳答案
不能在函数声明中使用实例变量。使用 textFields 数组调用该函数并传递参数。
func validateAllTextFields(textFields: [UITextField] ) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
你们类有一些人:
validateAllTextFields(textFields: [foodName, foodPortion, foodCalories])
或者您检查函数内部是否 textFields 为空并且您使用实例变量
func validateAllTextFields(textFields: [UITextField] ) -> Bool {
if textFields.count == 0 {
textFields = [foodName, foodPortion, foodCalories]
}
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
关于ios - 默认参数值错误: "instance member cannot be used on type viewcontroller",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884023/