So Im making a two UIscrollview in my view. I'm using Ray Wenderlich's Custom Image Picker. But when I load it, only shows 1 imagepicker. I want to be able to load two image picker. I think Im doing something wrong with initWithCoder part. Cant seem to initialize it properly. Is it possible to have two ivars self. Sorry kinda new to iphoneDev. Thanks for your help.
Here's my whole implementation:
- (id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
_images = [[NSMutableArray alloc] init];
_thumbs = [[NSMutableArray alloc] init];
//THIS IS WHERE I THINK ITS WRONG but the upper part seems to be okay.
_images2 = [[NSMutableArray alloc] init];
_thumbs2 = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void)addImage2:(UIImage *)image {
[_images2 addObject:image];
[_thumbs2 addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void) createScrollView {
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (void) createScrollView2 {
self.slotBg2 = [[UIView alloc] initWithFrame:CGRectMake(362, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView2];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs2.count; ++i) {
UIImage *thumb = [_thumbs2 objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked2:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView2 addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView2 setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (IBAction)buttonClicked:(id)sender {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 2){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 3){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
}
- (IBAction)buttonClicked2:(id)sender {
UIButton *button2 = (UIButton *)sender;
[button2 removeFromSuperview];
[_images2 objectAtIndex:button2.tag];
[_images2 removeObjectAtIndex:button2.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%lu.png", button2.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
[mode1 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
} else if(slotBG == 2 ){
[mode2 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage2:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images2 count]);
[self createScrollView2];
} else if( slotBG == 3){
[mode3 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
}
}
In your createScrollView2 method, you alloc self.slotBg2, but then only reference self.slotBg when adding to your view. Then you add your scrollview2 to the original slotBg.
Related
I am gettting images from documents directory. it's succesfully getiing. but when it's load on table it appear same images on table.
arrayOfImages = [[NSMutableArray alloc]init];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *stringPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%#",documentsDirectory);
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
for(i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
NSLog(#"%#",strFilePath);
if ([[strFilePath pathExtension] isEqualToString:#"JPG"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSLog(#"%#",imagePath);
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"%#",image);
[arrayOfImages addObject:image];
NSLog(#"%#",arrayOfImages);
}
}
}
For Table i m calling this code
saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
[saveImageView setImage:[arrayOfImages objectAtIndex:indexPath.row]];
[cell.contentView addSubview:saveImageView];
Try this in your cellForRowAtIndexPath method.
static NSString *CellIdentifier = #"Cell";
UIImageView *saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; // You cell initialization
saveImageView.tag = 1000;
[cell.contentView addSubview:saveImageView];
}
((UIImageView *)[cell.contentView viewWithTag:1000]).image = [arrayOfImages objectAtIndex:indexPath.row];
I'm new to iPhone development, I have used UIImagePickerController to capture the image manually, but i want to capture the image automatically, Is it possible to do that.
please help me.
Thanks in advance
Try This. In this I have saved the screen shot in photos album
-(void)screenShotCapture
{
//-- Screen Capture --------------------------------------------------------------------//
UIImage *image = nil;
UIGraphicsBeginImageContext(loginBgImgVw.frame.size);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(375, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:#"%#_Login_%#",providerIdStr,dateToday];
[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];
loginBgImgVw.frame = CGRectMake(10, 0, 1006, 669);
[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label removeFromSuperview];
//=--
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(#"path=--%#",paths);
NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:#"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
if ([screenCapturNameAry count] != 0)
{
if ([screenCapturNameAry containsObject:#"Login"])
{
[imageData writeToFile:savedImagePath atomically:NO];
}
}
UIImageWriteToSavedPhotosAlbum([self loadImage:#"Login_Provider"],self,#selector(image:didFinishSavingWithError:contextInfo:),NULL);
//--------------------------------------------------------------------------------------//
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error == nil)
{
NSLog(#"Login Image saved successfully.");
}
else
{
NSLog(#"Error occurred:%#",[error localizedDescription]);
}
}
You can get the saved image using following method
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
To take the screenshot you can use the following code.
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:#"screen.png" atomically:YES];
For Ratina display device you have to check:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);
Having a problem with my code, was able to have a preview with thumbnail with images in a UIScrollView. My images is from NSDocumentDirectory. I can delete from it though but I can delete from it (in terms of VIEW & in NSDocumentDirectory) PROPERLY when I start from the right to left position.
PROBLEM:
Now, I can delete anyway, But I have some several problems.
First, though I can delete, the view is not arranging, my rearrangeItems: method is not being called also.
Second,Then at first load I can delete anyway I like, but like what I said rearrangeItems: method is not being called, so their names
arent renamed.
Third, is at first load, I can delete in anyway, but when I exit the app, I can delete but my images in the NSDocu is not deleting.
Hope anyone could help me with this. Below is the preview of my code.
- (void)addImage:(UIImage *)imageToAdd {
[_images addObject:imageToAdd];
[_thumbs addObject:[imageToAdd imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
int row = floor(([_thumbs count] - 1) / 5);
int column = (([_thumbs count] - 1) - (row * 5));
UIImage *thumb = [_thumbs objectAtIndex:[_thumbs count]-1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside];
button.tag = [_images count] - 1;
// This is the title of where they were created, so we can see them move.s
[button setTitle:[NSString stringWithFormat:#"%d, %d", row, column] forState:UIControlStateNormal];
[_buttons addObject:button];
[scrollView addSubview:button];
// This will add 10px padding on the bottom as well as the top and left.
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
- (void) deleteItem:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
[saveMessage show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_buttons removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
[self rearrangeItems:button.tag];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
//NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
UPDATED: new rearrange method
- (void)rearrangeItems:(int)startIndex {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > startIndex) {
NSLog(#"called here");
// Version 2 ****************************
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
[fileManager removeItemAtPath: fullPath error:NULL];
// **************************************
button.tag -= 1;
// Version 2 ****************************
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[imageData writeToFile:fullPath atomically:YES];
// **************************************
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*61+16+60)];
}
}
}
}
You show "rearrangeButtons" but never use it - I assume the code above is out of date. In any case you have some small issues here:
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
[_images removeObject:button];
The first and last statements make no sense, what you should be using is:
[_images removeObjectAtIndex:button.tag];
[self rearrangeButtons:button.tag];
To just add a sanity check to the app, try adding this code to the end of rearrangeButtons:
int idx = 0;
for (UIButton *button in _buttons) {
NSLog(#"Going to query button at index %d", idx);
NSLog(#"Button at index %d is of type %#", idx, NSStringFromClass([button class]);
// if the button is not a UIView subclass, it won't have tag. If its a dealloced
// object then it probably will crash when you ask it its class...
if(button.tag != idx) NSLog(#"INDEX PROBLEM AT BUTTON ARRAY INDEC %d", idx);
++idx;
}
EDIT: code edited in loop to print out the object class
EDIT2: So I took your code and put it into a new project, ButtonManager. Essentially its OK but you have a few problems. First, you index the file names even if no file exists, so the indexes could get out of sync. Second, you use %lu format for a button.tag, but that is an integer so you should be using "%d". Lastly, you delete buttons from the array but not the images or the thumbnails.
If you download that project, you will see warnings in all the places you need to change to get to work properly. I am not sure why the button indexes got corrupted - maybe other code. In any case there is a data consistency test added to the code - sprinkle calls to that around in your code - if its ever fails then you know your problem is between the last good test and the latest failing one.
The project kicks off a "deleteItem:" message when it starts, and just keeps deleting items in the middle of the array as long as you tap YES.
Replace your functions with these
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[self rearrangeItems:button.tag];
}
}
- (void)rearrangeItems:(int)startIndex {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > startIndex) {
NSLog(#"called here");
[button removeFromSuperview];//remove the button from the scrollview
[_buttons removeObjectAtIndex:button.tag];//remove the button object from _buttons array
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
[fileManager removeItemAtPath: fullPath error:NULL];
button.tag -= 1;
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[imageData writeToFile:fullPath atomically:YES];
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*61+16+60)];
}
[scrollView setNeedsDisplay];
}
}
Hope this helps.
Im making a preview in my ViewController that all my Picked images in imagePicker will be in my scrollView,
Yes, I was able to make a preview of it in thumbnail, But when I'm logging it in my debugger, it seems to be that everytime my viewDidAppear, it also reAdds the scrollView, so the images count is being added again, making it harder to delete in view due to overlaping of the images. What I needed is to just refresh the scrollview whenever the view appears and when I'm adding a new image/s.
Here is a sneak preview of those codes I'm having problems for a long time:
- (id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
_images = [[NSMutableArray alloc] init];
_thumbs = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
[self createScrollView];
}
- (void) createScrollView {
[scrollView setNeedsDisplay];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
}
- (void)viewDidLoad
{
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 310, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,130.0f)];
[slotBg addSubview:self.scrollView];
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; 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]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
}
Help would be much appreciated.
And would using this be much of help, removing then adding. Or is this a way to just completely remove/delete all those subview completely, then REadd?
Thanks for those whose gonna help.
And could this be helpful? Thankyou
for(UIView *subview in [scrollView subviews]) {
if([subview isKindOfClass:[UIView class]]) {
[subview removeFromSuperview];
} else {
}
}
DELETE:
- (void)deleteItem:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
[_images removeObject:button];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
}
Here is a working example : Google Code
I wrote out the code, and I have this. It will align the view to be 5 wide, and however tall it has to be, and the scrollview will change height.
You will need to create a new NSMutableArray named _buttons that will contain a list of your buttons.
- (void)addImage:(UIImage *)imageToAdd {
[_images addObject:imageToAdd];
[_thumbs addObject:[imageToAdd imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
int row = floor(([views count] - 1) / 5);
int column = (([views count] - 1) - (row * 5));
UIImage *thumb = [_thumbs objectAtIndex:[_thumbs count]-1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside];
button.tag = [views count] - 1;
// This is the title of where they were created, so we can see them move.s
[button setTitle:[NSString stringWithFormat:#"%d, %d", row, column] forState:UIControlStateNormal];
[_buttons addObject:button];
[scrollView addSubview:button];
// This will add 10px padding on the bottom as well as the top and left.
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
- (void)deleteItem:(id)sender {
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[views removeObjectAtIndex:button.tag];
[_buttons removeObjectAtIndex:button.tag];
[self rearrangeButtons:button.tag];
}
- (void)rearrangeButtons:(int)fromTag {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > fromTag) {
button.tag -= 1;
}
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
}
}
Note: In the rearrangeButtons method, it is possible to animate the changes.
Here is the code to rearrange the files:
- (void)rearrangeButtons:(int)fromTag {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > fromTag) {
// Create name string
NSString *imageName = [NSString stringWithFormat:#"images%i.png", button.tag];
// Load image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFile = [paths objectAtIndex:0];
NSSting *oldFilePath = [documentFile stringByAppendingPathComponent:imageName];
NSData *data = [[NSData alloc] initWithContentsOfFile:oldFilePath];
button.tag -= 1;
// Save the image with the new tag/name
NSString *newImageName = [NSString stringWithFormat:#"images%i.png", button.tag];
NSString *newFilePath = [documentFile stringByAppendingPathComponent:newImageName];
[data writeToFile:newFilePath atomically:YES];
// Delete the old one
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err = nil;
if (![fileManager removeItemAtPath:file error:&err]) {
// Error deleting file
}
}
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
}
}
I'm having trouble removing image in my scrollView, i put my images in UIScrollView then add button, when clicked will prompt an alert view asking if you want to delete it. When yes, deletes in my NSDocumentDirectory but not in my View. My images is from NSDocumentDirectory picked from an ImagePicker.
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
[self createScrollView];
}
- (void) createScrollView {
[scrollView setNeedsDisplay];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
}
- (IBAction)buttonClicked:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
[saveMessage show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
- (void)viewDidLoad
{
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 310, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,130.0f)];
[slotBg addSubview:self.scrollView];
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
You are calling createScrollView each time you add an image to your array. What it seems to be doing is creating buttons containing the same image on top of each other. Your code seems to be removing it from the view, but it looks like there are similar buttons just below it. So call createScrollView only after you've added all the images and remove it from your addImage:.
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
[self createScrollView];
//after deleting the image from document directory just call viewDidAppear again...
[self viewDidAppear:yes];
Hope this will help you...
set tag value to button.then get the button in the following function by
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIButton *btn = (UIButton*)[scrollview viewWithTag:button.tag];
//your button tag
[btn removeFromSuperView];
}
try this method :
- (void)removeObjectWithTag:(int)objectTag
{
[_thumbs removeObjectAtIndex:objectTag];
for (UIView *view in scrollView.subviews)
{
[view removeFromSuperview];
}
scrollView.contentSize = CGSizeZero;
[self createScrollView];
}