Search code examples
iosswiftfunc

Change value of var outside the function


I declared the var imagePicked = 0 at the top of my class. Now when I change the value of imagePicked inside an IBAction like here:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var titelbild: UIButton!
@IBOutlet weak var profilbild: UIButton!


let imagePicker = UIImagePickerController()
var imagePicked = 0



override func viewDidLoad() {
    super.viewDidLoad()


    imagePicker.delegate = self
 //   imagePicker.allowsEditing = false
  //  imagePicker.sourceType = .PhotoLibrary


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func titelbildtapped(sender: AnyObject) {


 //   if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){


    imagePicked == 1

        imagePicker.allowsEditing = false
        imagePicker.sourceType = .PhotoLibrary


        self.presentViewController(imagePicker, animated: true, completion: nil)



  //  }


}


@IBAction func profilbildtapped(sender: AnyObject) {


    imagePicked == 2

        imagePicker.allowsEditing = false
        imagePicker.sourceType = .PhotoLibrary


        self.presentViewController(imagePicker, animated: true, completion: nil)

    print ("output")

}





func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {


if imagePicked == 1 {

    titelbild.setImage(pickedImage, forState: UIControlState.Normal)
       // titelbild.imageView?.image = pickedImage

 } else if imagePicked == 2 {
        profilbild.setImage(pickedImage, forState: .Normal)        }

    }
    dismissViewControllerAnimated(true, completion: nil)
}



func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

}

the value of imagePicked appears to be still 0 instead of 2. How can I change the value of it, so it is not only changed inside the function i changed it?


Solution

  • ok. the problem is in your titelbildtapped / profilbildtapped functions. there you have to assign the values 1 / 2 with a single = instead of double == which checks for equality.

    so change imagePicked == 1 / imagePicked == 2 to imagePicked = 1 / imagePicked = 2 in those functions and it should work!