I'm trying to pass a variable from a child view (inputPopUp.swift) to a parent view using setter and getter functions. Here is the code in my child view:
var char: String!
var buttonPressed = String()
@IBAction func addButtonPressed(sender: AnyObject) {
buttonPressed = "addButton"
setChar("+")
getChar()
self.removeAnimate()
}
@IBAction func minusButtonPressed(sender: AnyObject) {
buttonPressed = "minusButton"
setChar("-")
self.removeAnimate()
}
@IBAction func divideButtonPressed(sender: AnyObject) {
buttonPressed = "divideButton"
setChar("/")
self.removeAnimate()
}
@IBAction func multiplyButtonPressed(sender: AnyObject) {
buttonPressed = "multiplyButton"
setChar("*")
self.removeAnimate()
}
//setter method
func setChar(var thisChar: String){
char = thisChar
}
//getter method
func getChar()-> String{
if (buttonPressed == "addButton"){
char = "+"
}
if (buttonPressed == "minusButton"){
char = "-"
}
if (buttonPressed == "divideButton"){
char = "/"
}
if (buttonPressed == "multiplyButton"){
char = "*"
}
return char
}
I am trying to access the 'char' variable in my parent view like so, however it is returning nil - presumably because I am calling a new instance of the function.
@IBAction func runButtonPressed(sender: AnyObject) {
inputPopUp().getChar()
}
I would also like to update a label in my parent view, based on the button click within my child view. I am trying to implement Key-Value Observation. Here's what I've got so far.
class ObserveChar: NSObject {
dynamic var char = String()
func updateChar(){
char = String()
}
}
private var myContext = 0
class Observer: NSObject {
var objectToObserve = ObserveChar()
override init(){
super.init()
objectToObserve.addObserver(self, forKeyPath: "char", options: .New, context: &myContext)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &myContext {
println("Char updated: \(change[NSKeyValueChangeNewKey])")
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "char", context: &myContext)
}
}
Ok,Maybe you can set the child view as a property of parent view,maybe like this
var inputPopView : inputPopUp /**<initialize it somewhere */
and then you can use it like this
@IBAction func runButtonPressed(sender: AnyObject) {
self.inputPopView.getChar()
}