Can you please tell me how to change UIImageView's Image in ViewController A from View Controller B?
My Xcode version is Xcode 7, with Swift 2.0,
Thank you.
As thefredelement you can use NSNotification
for that like in your ViewController B just add this code when you are dismissing view to ViewController A:
@IBAction func goBack(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
And in your viewController A add this code in your viewDidLoad
method:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList:", name:"refresh", object: nil)
}
And add this helper method in same class:
func refreshList(notification: NSNotification){
println("parent method is called")
//you can change your UIImageView's Image here.
}
Now when ever you press button from ViewController B it will call this method from ViewController A.
Note: I have tested this with Xcode 6.4 and I think it will work fine with Xcode 7 too.
In Swift 4
1st View Controller
@IBOutlet weak var imageView: UIImageView! // ImageView
func goToImageChooserClass () {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let secondVC = storyBoard.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC
secondVC.firstVC = self // Object in 2nd Controller that is a FirstVC Object
self.present(secondVC, animated:true, completion:nil)
}
2nd View Controller
class SecondVC {
...
var firstVC:FirstVC! // Object representing the firstVC
...
func goBack (){
self.dismiss(animated: true, completion: {
self.firstVC.imageView = {insert your image here}
})
}
}
Here is how you work with NSUserDefaults
You write like this :
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(image!, forKey: "image")
and read like this :
let defaults = NSUserDefaults.standardUserDefaults()
let image = defaults.objectForKey("image") as! UIImage
and set it to the imageView
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.