I'm using the Custom Picker by ray, when I press a button a picker is pop-ups then when image is chosen it will dismiss the picker and displayed the image in UIImageView. I put in the viewWillAppear but when I go to another ViewController the image chosen disappears. How to maintain the chosen in UIImageView to be displayed even after going to different View Controllers, only will it change if another image is chosen again.
- (void)viewWillAppear:(BOOL)animated {
secondView.image = _imagePicker.selectedImage;
}
- (IBAction)chooseCustomImageTapped:(id)sender {
_imagePicker = [[CustomImagePicker alloc] init];
_imagePicker.title = #"Choose Custom Image";
for(int i = 0; i <= 10; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[_imagePicker addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
[self presentModalViewController:_imagePicker animated:NO];
}
I think you should take your image in UIImage object just after selection done UIImage *image = _imagePicker.selectedImage;, and retain it till next change. Then set that image to your image view secondView.image = image;.
Did you alloc a new view controller when you go to the specified view controller? If so, when you go to a new view controller, you alloc it, so all the datas has been initalized.
use the pickerview delegate function.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
// put your logic here.
NSUserDefaults *udf=[NSUserDefaults standardUserDefaults];
[udf setObject:#"Imagename" forKey:#"LastSelectImage"];
}
accordingly your image has change your image name here.
Related
I'm currently trying the iCarousel Multiple Carousel example.
Here in my array, I've add images with NSMutableDictionary:
I have two of these: ( myImages and myImages2 for my two slot in carousel loaded in ViewDidLoad)
self.myImages = [NSMutableArray array];
for(int i = 0; i <= 10; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedPath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"myImages%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedPath]){
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedPath] forKey:#"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index"];
[images addObject:container];
[container release]; // if not using ARC
}
}
in my iCarousel:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
if (carousel == carousel1)
{
NSDictionary *obj = [items1 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:#"items1"]];
view.tag = index;
}else
{
NSDictionary *obj = [items2 objectAtIndex:index];
view = [[UIImageView alloc] initWithImage:[obj objectForKey:#"items2"]];
view.tag = index;
}
return view;
}
In another View, these arrays are also loaded, the user has a chance to pick an image to compare to with,
when an user pick an image an int equivalent to its tag is pass to where my two Carousel is.
Here is how I compare them:
NSInteger image = [prefs integerForKey:#"image"];
NSInteger image1 = [prefs integerForKey:#"image2"];
if (image == [(UIImageView*)[self.carousel1 currentItemView] tag] || image2= [(UIImageView*)[self.carousel2 currentItemView] tag] || ) {
I delete an index this way:
NSInteger index = carousel1.currentItemIndex;
[carousel1 removeItemAtIndex:index animated:YES];
[items1 removeObjectAtIndex:index];
I think I'm deleting it the wrong away, because the index arent updated, what i wanted is to maintain its index not adjust like this images right here:
Deleting in NSMutableArray
If I understand what you are trying to do now, which is to move the two carousels until the middle one matches, then to not have the indexes simply go away, then you could just rather than removing the item from the array, fill the location you are trying to delete with a nil image (or a valid image with the backing of your choosing), and a tag stating it has already been matched.
This is all of course dependent on whether my understanding of what you want is valid.
I have a UITableView that is populated using a NSMutableArray . I am using xcode 4.2
the data in the NSMutable array stays in case I switch applications but it gets erased in these two cases :
1-the user switch view and come back .
2-the application is completley closed (i.e. the user double click on the Main button and remove it from the list of running application)
here is the code that I am using
-(NSString *)dataFilePath{
NSString *dataFilePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
dataFilePath = [documentDirectory stringByAppendingPathComponent:#"Test App-Info.plist"];
return dataFilePath;
}
-(void)saveData{
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
- (void)loadData
{
data = [NSKeyedUnarchiver unarchiveObjectWithFile:self.dataFilePath];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
...
//saving the history
NSArray *archivedArray =[NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
}
else {
[self loadData];
[mainTableView reloadData];
}
}
Please let me know if I am missing something
Thanks
Edited :
the save data function is loaded in two locations :
1- the app that I am developing scans QR codes , so save data is called in the following function :
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
....
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results){
// EXAMPLE: just grab the first barcode
break;
}
if(!symbol)
return;
// EXAMPLE: do something useful with the barcode data
theBarcodeString = symbol.data;
//adding the string to the list
[data addObject:theBarcodeString];
[self saveData];
[mainTableView reloadData];
[self endText];
stringLabel.text=theBarcodeString;
...
}
it is also called in when the data is edited :
-(IBAction)editTable{
UIBarButtonItem *leftItem;
[mainTableView setEditing:!mainTableView.editing animated:YES];
if (mainTableView.editing) {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(editTable)];
}
else {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editTable)];
}
[self saveData];
[mainTableView reloadData];
}
You need to look into the following calls:
applicationDidEnterBackground
applicationWillEnterForeground
applicationDidBecomeActive
applicationWillTerminate
They are all methods of UIApplication. Your needs will dictate which of the above store and restore your data depending on when it should happen.
In my view I have several fields, some of them are hidden. There is a segmentController with 2 option. To enable the "take a photo" button it must be set on 1. So I fill the fields i see, press the segmentedController on 1 position, fill another field which was hidden and take a picture.When I came back from the photo view, all the fields are empty and the selector is deselected (setSelectedSegmentIndex:-1).If I press again this selector on 1 position, the hidden field is empty, but the UIImageView show the photo i've taken...if I set in viewDidLoad setSelectedSegmentIndex:1, as I dismiss the photoView, all the fields are showed empty (again the UIImageview show the picture).I also tried to save the contents of every field in variables and put everything back in viewDidLoad in this way
if (([name length] != 0) || ([price length] != 0) || (category length] != 0)) {
//restore all the fields from those NSString variables and set segment on 1
}
but the app crashs.I have this problem just if I run the app on the iPhone, not on the simulator, because the simulator takes its image right from the camera roll.
This is the code for taking photos.
-(IBAction)takePhoto:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.imgPicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
} else {
imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
[self presentModalViewController:self.imgPicker animated:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
int r = arc4random() % 9999;
NSDate *date = [NSDate date];
NSString *photoName = [dateNameFormatter stringFromDate:date];
photoName = [photoName stringByAppendingString:[NSString stringWithFormat:#"%d", r]];
if (imagePath) {
[imagePath release];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", photoName]];
[imagePath retain];
UIImage *picture = [[info objectForKey:UIImagePickerControllerOriginalImage] retain];
// ----- CODE FOR SCALE THE IMAGE ----- //
if (picture.size.width == 1936) {
picture = [picture scaleToSize:CGSizeMake(480.0f, 720.0f)];
} else {
picture = [picture scaleToSize:CGSizeMake(720.0f, 480.0f)];
}
photoPreview.image = picture;
photoPreview.contentMode = UIViewContentModeScaleAspectFit;
CGRect frame = photoPreview.frame;
if (picture.size.width == 480) {
frame.size.width = 111.3;
frame.size.height =167;
} else {
frame.size.width = 167;
frame.size.height =111.3;
}
photoPreview.frame = frame;
// ----- ----- - END CODE - ----- ----- //
NSData *webData = UIImagePNGRepresentation(picture);
//CGImageRelease([picture CGImage]);
[webData writeToFile:imagePath atomically:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
when using the UIImagePickerController the system usually calls a memory warning. This cause all of the views that are loaded to unload in order to free some memory.
My guess that in your case, you are not saving the state correctly and on the second call to the "viewDidLoad:" and you are unable to re-initiate the view.
you should write the viewDidLoad in a way that it can be called more than once and will still behave the same.
My app consists of an image gallery. It is a scroll view which displays pics retrieved from the sqlite db. User can scroll the images, add or delete images etc. I can add a picture to the gallery dynamically. But the problem comes when I need to implement the delete functionality. I use the following code but even after calling removeFromSuperView the image is not getting removed from the scrollview.
-(void)deleteDeck{
if(selectedEditDeck!=0){
[deck deleteSelectedDeck:selectedEditDeck]; //deleting from database
//problem starts here ***
[(UIImageView*)[decksGallery viewWithTag:selectedEditDeck-1]removeFromSuperview];
[self loadGallery];
selectedEditDeck=0;
//Ends here*****
[tableData release];
tableData=[NSMutableArray array];
[self showCardNamesinTable];
[aTableView reloadData];
}
I have already created the uiscrollview in the loadview method. Then to refresh the view after every deletion and addition of images so that I can display the updated gallery, I use the following piece of code:
-(void)loadGallery{ //Reloading all for adding a single deck image.
//Database part****
NSString *sqlStr = [NSString stringWithFormat:#"select first_card from decksTable"];
char *sql = (char*)[sqlStr UTF8String];
kidsFlashCardAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSMutableArray *galleryImagesArray=[appDelegate.dbConnection fetchColumnFromTable:sql col:0];
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *docDirectory = [sysPaths objectAtIndex:0];
numberofImages = [galleryImagesArray count];
printf("number is %d",numberofImages);//Database part of code ends here
//In the following fragment of code I add images to UIscrollView
for (int i = 0; i < [galleryImagesArray count]; i++) {
CGFloat yOrigin = i * 65;
NSString *filePath = [NSString stringWithFormat:#"%#/%#", docDirectory,[galleryImagesArray objectAtIndex:i]];
galleryImage = [[UIImageView alloc] initWithFrame:CGRectMake(yOrigin+140, 15,50,50 )];
//galleryImage.tag=[galleryImagesArray count];
galleryImage.tag=i;
printf("THE TAG IS %d",galleryImage.tag);
galleryImage.clipsToBounds=YES;
galleryImage.layer.cornerRadius=11.0;
galleryImage.backgroundColor=[UIColor clearColor];
galleryImage.image =[UIImage imageWithContentsOfFile:filePath];
[decksGallery addSubview:galleryImage];
[galleryImage release];
}
decksGallery.contentSize = CGSizeMake(115*[galleryImagesArray count], 80);
//[decksGallery reloadInputViews];
Make sure your [decksGallery viewWithTag:selectedEditDeck-1] is not returning nil and the image was actually deleted from your db before the refresh code running.
In addition, you are setting imageView.tag = i; in your creation code, since the i would be 0 which is the tag's default value for every UIView, you'd better fix your creation code as well.
If you just want to remove the image from your imageView, you can also do imageView.image = nil;
UIImageView*imageView = (UIImageView*)[decksGallery viewWithTag:selectedEditDeck-1];
[imageView removeFromSuperview];
imageView = nil;
I am using the ImageDemo template and it works great if I code in an image from the bundle but when I try and load them from directories I have created in my app I have no luck.
Code:
- (AQGridViewCell *) gridView: (AQGridView *) aGridView cellForItemAtIndex: (NSUInteger) index
{
static NSString * PlainCellIdentifier = #"PlainCellIdentifier";
AQGridViewCell * cell = nil;
ImageDemoGridViewCell * plainCell = (ImageDemoGridViewCell *)[aGridView dequeueReusableCellWithIdentifier: PlainCellIdentifier];
if ( plainCell == nil )
{
plainCell = [[[ImageDemoGridViewCell alloc] initWithFrame: CGRectMake(0.0, 0.0, 200.0, 150.0)
reuseIdentifier: PlainCellIdentifier] autorelease];
plainCell.selectionGlowColor = [UIColor lightGrayColor];
}
NSString *fileName = [NSString stringWithFormat:#"%#/%#_tn.jpg",[manufacturerID stringValue], [[[self.collectionItems objectAtIndex:index] valueForKey:#"PhotoName"] stringByReplacingOccurrencesOfString:#" " withString:#"%20"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *savePath =[documentsPath stringByAppendingPathComponent:fileName] ;
NSData *imageData = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:savePath];
if (fileExists) {
imageData = [NSData dataWithContentsOfFile:savePath];
} else {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"NoImageAvailableThumbNail" ofType:#"png"];
imageData = [NSData dataWithContentsOfFile:filePath];
}
UIImage *myImage = [UIImage imageWithData:imageData];
NSLog(#"%#", myImage);
if (myImage==nil) {
NSLog(#"NO IMAGE");
}
plainCell.image = myImage;
cell = plainCell;
return ( cell );
}
I code I am using to pull the image data I know works because I use it all over in other places in my app and I am checking for nil when I set the property on the AQGridViewCell:
- (void) setImage: (UIImage *) anImage
{
_imageView.image = anImage;
[self setNeedsLayout];
}
I don't see the check for a nil UIImage in your example there. Are you certain it's being loaded correctly? Try creating the image on one line and setting it on another so you can see it being created in the debugger. For reference, I do something similar with cached book cover images in the Kobo app, and that works. One difference though is that I use the C methods to load a UIImage from a PNG file. Something like UIImageFromPNGData(), off the top of my head (sorry replying by iPhone right now).
The only other thing I can think to check is whether the image view is hidden for some reason. Printing it in the debugger should tell you that, along with it's size, layout, etc.