ViewController has a textField called userInput which allow user to add a value, so i want to change the label name when user press the button of calculate. I used a class to modify label name, when calling viewController label from inside the class xcode shows "viewController does not have a member name userAnswer" But my code does have a label called userAnswer.
import UIKit
class ViewController2: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet var userInput: UIPickerView!
@IBOutlet var userTo: UIPickerView!
@IBOutlet var userValue: UITextField!
@IBAction func calculate(sender: AnyObject) {
var textboxValue = userValue.text.toInt()
if textboxValue != nil {
if selection1 == 0 {
let milimeter = Milimeter()
milimeter.toCnverter(textboxValue!, item: selection2)
userAnswer.text = " "
} else if selection1 == 1 {
} else if selection1 == 2 {
} else if selection1 == 3 {
} else if selection1 == 4 {
}
} else {
userAnswer.text = "Please enter a Value"
}
}
@IBOutlet var userAnswer: UILabel!
let length1 = ["Milimeter","Centimeter","Inch","Meter","Kilometer"]
let length2 = ["Milimeter","Centimeter","Inch","Meter","Kilometer"]
var selection1 = 0
var selection2 = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
userInput.delegate = self
userInput.dataSource = self
userTo.delegate = self
userTo.dataSource = self
}
class Milimeter {
func toCnverter(value: Int, item: Int) {
switch item {
case 0:
userAnswer.text = " " // i can't access , shows error
case 1:
println("Inch")
case 2:
println("Kilometer")
default:
println(" ")
}
}
}
}
It seems that you have forgotten to connect the UILabel
from the UIStoryboard
, with the UILabel
in your code. To be 100% sure, delete the variable from your code and reconnect the outlet from the UIStoryboard
to your code.
Edit after seeing the whole code:
Your class
Millimeter does not know of your UILabel
since it is not an attribute of it, but an attribute of the UIViewController
.
My recommendation: func toConverter
should return what it converts. That makes it also testable -> func toConverter(value: Int, item: Int) -> String
Your if-statement
would look like this:
if selection1 == 0 {
let milimeter = Milimeter()
userAnswer.text = milimeter.toCnverter(textboxValue!, item: selection2)
}
Here is some more information on Access Control
in swift