UIImageVIew.image isn't be changed - ios

I'm newbie to iOS programming, and trying to developer "FoodTracker" in Swift tutorial. Below is all my code.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
nameTextField.resignFirstResponder()
//UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
//Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
//Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
//Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithinfo info: [String : AnyObject]) {
//The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
//hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = textField.text
}
}
The app is executed normally but the image can't be changed.
The normal process is click the image > select any image from Camera roll > change the image of idle screen. The problem is last step, "change the image of idle screen."
Which point is my mistake? I have compared my code with example code in tutorial again and again, but I couldn't find something helpful. Please help me.

2 things:
First declare the
let imagePicker = UIImagePickerController();
as an instance variable and then set it's delegate to self in viewdidload
override func viewDidLoad() {
super.viewDidLoad();
imagePicker.delegate=self;
}
This way it's set only once (rather reseting for each func call)
Second I suggest to use :
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
photoImageView.image=image;
}
instead of (didFinishPickingMediaWithinfo ...), which made exactly for picking image, just as you need and you don't need casting.
Here is a simplified example:
image picker example
Hope it helped

Finnaly, I figure out the solution. But it's little trivial.
The problem is Language version. I used XCode 6.4 and Swift 1.2.
But the homepage used XCode 7.0 beta and Swift 2.0.
This is the reason of my problem. And now, all works fine.
Thank you for all my responders.

Did you look at selectedImage variable? Does it nil? Try to setup breakpoint to line after setting selectedImage.

Related

Touched not working in Xcode simulator (apple official tutorial 'FoodTracker')

I'm working on an official Apple tutorial to learn iOS.
But I did the same, but the touch does not work in the simulator.
I tried turning Xcode off and on and copying and pasting the example file but it still doesn't touch. Or is there anything else you should try?
I need help.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoimageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
mealNameLabel.text = textField.text
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as?
UIImage else {
fatalError("Expected a dictionary containing an image, but was provided folowing: \(info)")
}
// Set photoImageView to display the selected image.
photoimageView.image = selectedImage
// dismiss picker
dismiss(animated: true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
#IBAction func setDefaultLabelText(_ sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
You should add isUserInteractionEnabled as true with Storyboard and add Tap Gesture Recognizer and link (or update this link) #IBAction func selectImageFromPhotoLibrary with Storyboard

Ios with UIImagePickerController cause SIGABRT error

I am very new to iOS development, and as I follow the instruction from here, although it already told me to add a privacy - photo library usage to my properties item inside the info.plist to solve the sigabrt error, and I already did add that, it still show the sigabrt error. I am currently running the code from a simulator. Is it because I run it in simulator instead of real device?
Here is the viewcontroller
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UITextFieldDelegte
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
mealNameLabel.text = textField.text
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
//MARK: Actions
#IBAction func setDefaultLabelText(_ sender: UIButton) {
mealNameLabel.text = "Default Text"
}
#IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
}

Following iOS Tutorial - Cannot get image picker to display

So I'm new to iOS Development and I'm finally onto this step: https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html#//apple_ref/doc/uid/TP40015214-CH6-SW1
I've followed the guide step-by-step and for some reason, when I run my app, I click on the Image View and nothing pops up. My code is exactly like Apple's with the exception of nameTextField being businessNameTextField and businessNameLabel. Here's my ViewController.swift file
//
// ViewController.swift
// Example (Sample 1)
//
// Created by lewlsaucengravy on 4/9/17.
// Copyright © 2017 Example. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Properties
#IBOutlet weak var businessNameLabel: UILabel!
#IBOutlet weak var businessTextField: UITextField!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
businessTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
businessNameLabel.text = textField.text
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if user cancelled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
//MARK: Actions
#IBAction func completeProfile(_ sender: UIButton) {
businessNameLabel.text = "test"
}
#IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard.
businessTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
}
My AppDelegate.swift file is is the default when creating the project, so nothing to show there.
Here's the Main.storyboard:
I'm trying to avoid just deleting the app and starting over because I want to get in the habit of troubleshooting and learning what I'm doing wrong.
From what I understand, and feel free to correct me if I'm wrong, when the user clicks on the Image View, it's calling the selectImageFromPhotoLibrary function from which I've defined under Actions, and everything is supposed to go from there.
Edit
It looks like the issue may have been the "User Interaction Enabled" checkbox that I forgot to check. It's the only thing I changed since posting the question and apparently it's working now.
Ensure the User Interaction Enabled checkbox is checked:
From what I am thinking, you did not have set the following parameters in your plist:

iOS - Tap Gesture issue on image view

I am slowly working my way through Apple's learn developing for Swift and I keep running into an issue with my tap gesture. I have re-created the project numbers times all with the same outcome.
I add a tap gesture to an image view and this should open the photo library from my computer. Nothing happens.
When I download and run the sample file from Apple everything works. When I copy and paste the code from Apple's to mine, again, nothing happens. I have gone through everything that I can but feel that I am missing something.
Here is my code. Apple's code is below:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// handle the text fields user input through delegate callbacks
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the Keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = textField.text
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// dismiss the picker if user cancels
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set the photoviewimage to be the selected image
photoImageView.image = selectedImage
// Dismiss the picker
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the Keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only Allow pictures to be selected and not taken
imagePickerController.sourceType = .PhotoLibrary
// make sure the viewcontroller is notified when the user selects an image
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
Here is Apple's code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = textField.text
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
Working Code from Anbu
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIImageView!
override func viewDidLoad() {
let tapgesture = UITapGestureRecognizer(target: self, action: Selector("imagepressed"))
photoImageView.userInteractionEnabled = true
photoImageView.addGestureRecognizer(tapgesture)
super.viewDidLoad()
// handle the text fields user input through delegate callbacks
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the Keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = textField.text
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// dismiss the picker if user cancels
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set the photoviewimage to be the selected image
photoImageView.image = selectedImage
// Dismiss the picker
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
func imagepressed () {
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only Allow pictures to be selected and not taken
imagePickerController.sourceType = .PhotoLibrary
// make sure the viewcontroller is notified when the user selects an image
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
/* #IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
let tapgesture = UITapGestureRecognizer(target: self, action: Selector("imagepressed"))
photoImageView.userInteractionEnabled = true
photoImageView.addGestureRecognizer(tapgesture)
// Hide the Keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only Allow pictures to be selected and not taken
imagePickerController.sourceType = .PhotoLibrary
// make sure the viewcontroller is notified when the user selects an image
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
*/
#IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
The easiest way I found that solved the issue is to click the checkbox that says "User Interaction Enabled" in the Attributes Editor for the Image View. Screenshot
do like
The reason ,by default the UIImageview userInteraction is false, so you need to enable manually
Step-1
let tapGesture = UITapGestureRecognizer(target:self, action:Selector("imagePressed"))
photoImageView.userInteractionEnabled = true // this line is important
photoImageView.addGestureRecognizer(tapGesture)
Step-2
func imagePressed()
{
//do Your action here whatever you want
}
Your code is perfectly fine. The problem is with the UIImageView in the story board. The user interaction option is unchecked.
So you just have to enable this option in storyboard.
Go to your story board.
Select your UIImageView (you named it photoimageview)
Now in “Attribute Inspector” look for user interaction enabled, it should be “checked”
Now run your project it will work.
Where have you added the UITapGestureRecognizer for the image view? If you added it in Storyboard, did you connect it to the selector selectImageFromPhotoLibrary:?

Swift tutorial foodtracker: tap gesture method not called

I am playing around with the apple swift tutorial for the Foodtracker and try to open now the Photo library with the tap gesture.
//
// ViewController.swift
// FoodTracker
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var mealPhotoView: UIImageView!
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
mealPhotoView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
print("selectImage called!")
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func setDefaultLabelText(sender: AnyObject) {
nameLabel.text = "Default Meal name"
}
override func viewDidLoad() {
super.viewDidLoad()
// Handle the user input on textfield through delegate callback (self == this)
nameTextField.delegate = self
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
nameLabel.text = textField.text
}
}
anyhow when the simulator starts up and I tap on the photo the library view is not shown. I even cannot see me debugging message.
I already did remove the outlets and actions and did the whole process again by adding the UIImageView Outlet, add the gesture recognizer, add the action of the gesturerecognizer but still not happening what it should.
I have found the problem - I did not enable the User Interaction which is set to false by default.

Resources