File ios problems - unrecognized selector - iphone

This is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
textBox = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 300, 40)];
[textBox setDelegate:self];
[self.view addSubview:textBox];
[textBox release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(saveText) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Save" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"PATH---> %#",dirPaths);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFile = [docsDir stringByAppendingPathComponent: #"datafile.dat"];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFile])
{
// Read file contents and display in textBox
NSData *databuffer;
databuffer = [filemgr contentsAtPath: dataFile];
NSString *datastring = [[NSString alloc] initWithData: databuffer encoding:NSASCIIStringEncoding];
textBox.text = datastring;
[datastring release];
}
[filemgr release];
[super viewDidLoad];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)saveText:(id)sender
{
NSLog(#"Text saved");
}
If I try executing this I am getting an error saying
"2013-02-18 12:43:46.194 FileExample[1475:207] -[FileExampleViewController saveText]: unrecognized selector sent to instance 0x682e730"
I am new to iOS and am not able to identify or understand or debut this error.

Change your this line
[button addTarget:self action:#selector(saveText) forControlEvents:UIControlEventTouchUpInside];
with this
[button addTarget:self action:#selector(saveText:) forControlEvents:UIControlEventTouchUpInside];
OR
do this
- (void)saveText // removed " :(id)sender "
{
NSLog(#"Text saved");
}

Related

Deleting in NSDocumentDirectory and UIScrollView

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.

UIScrollView updating/loading wrongly

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)];
}
}
}

Button deletes in array but not in View

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];
}

UIScrollView not loading/updating properly

Im having problem with my UISCrollView, UIScrollVIew is in my View2Controller, my UIScrollView has thumbnail of images, which I imported from my ImagePicker picked images(multiple/single images). I have put my [self createScrollView]; in viewDidAppear, So at my first load of the view only the UIScrollView, obviously because I havent picked images yet. So after I picked its not updating in my view. But my images.count are updating in the my debugger. It's not updating in View, but when I go to another ViewController then return again to View2Controller, it loads the images in my UIScrollView,then when I add again images it's not updating. Why is it like that?.
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (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)viewDidAppear:(BOOL)animated
{
[self createScrollView];
}
- (void)viewDidLoad
{
[super 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];
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]);
}
EDIT: (In this part, the image can't be deleted from the view. But in my NSDocumentDirectory it is deleted, )
- (IBAction)buttonClicked:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE IMAGE?"
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 = _clickedButton1;
[button removeFromSuperview];
[_images1 objectAtIndex:button.tag];
[_images1 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");
}
viewDidAppear: is only called once you go to a view. So when you are 'adding' the images you are only adding them to the _images array, they are not displayed because you are not adding them to the screen. They are displayed when you leave the view and come back because viewDidAppear: is called again.
To fix this, use addImage: to also add it to the current view.
- (void)addImage:(UIImage *)image {
int row = ?;
int column = ?;
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
UIImage *thumb = [_thumbs objectAtIndex:_thumbs.count-1];
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 = _thumbs.count-1;
[scrollView addSubview:button];
}
Only problem of course is how to determine the placement, aka column and row. You can do this by getting the last thumb's frame and figuring out where to place it according to screen bounds.
Another Fix
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
[self createScrollView];
}
You need to call createScrollView after you have updated your array of images. Maybe try moving [self createScrollView]; to the end of your viewDidLoad method? Either way, you need to call createScrollView after you have added all of your images.

button.tag property is not working in UItableView cell

I am adding download button in cell's accessory view ..my code is
button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:#"download.png"];
[button setImage:image forState:UIControlStateNormal];
//[button setTitle:#"Download" forState:UIControlStateNormal];
[button setFrame: CGRectMake( 110.0f, 3.0f, 80.0f, 30.0f)];
[button addTarget:self action:#selector(someAction) forControlEvents:UIControlEventTouchUpInside];
button.tag = indexPath.row;
cell.accessoryView = button;
And I want to pass file name from cell 's index path but this is not working It only takes first row...
- (void)someAction {
[self.activityIndicator startAnimating];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [NSString stringWithFormat:#"/%#",[metaArray objectAtIndex:button.tag]];
NSLog(#"%#", button.tag);
NSString *path = [NSString stringWithFormat:#"%#/Downloaded Data/%#",[paths objectAtIndex:0],file];
// NSString *loadFileName = [NSString stringWithFormat:#"/%#/%#",Name,file];
[self.restClient loadFile:file intoPath:path];
NSLog(#"Downloaded:%#",file);
}
This crashing because of button.tag = indexpath.row
and if I don't pass button.tag = indexpath.row it is passing only first row
please help
tag is an integer property. You are trying to print it as object in NSLog. You have to print it like this, NSLog(#"%d", button.tag);
Actually you have to assign individual download buttons to each cell.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:#"download.png"];
[button setImage:image forState:UIControlStateNormal];
//[button setTitle:#"Download" forState:UIControlStateNormal];
[button setFrame: CGRectMake( 110.0f, 3.0f, 80.0f, 30.0f)];
[button addTarget:self action:#selector(someAction:) forControlEvents:UIControlEventTouchUpInside];
button.tag = indexPath.row;
cell.accessoryView = button;
And define your someAction method like this,
- (void)someAction:(id)sender {
UIButton *button = (UIButton *)sender;
NSLog(#"%d", button.tag);
[self.activityIndicator startAnimating];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [NSString stringWithFormat:#"/%#",[metaArray objectAtIndex:button.tag]];
NSString *path = [NSString stringWithFormat:#"%#/Downloaded Data/%#",[paths objectAtIndex:0], file];
//NSString *loadFileName = [NSString stringWithFormat:#"/%#/%#",Name,file];
[self.restClient loadFile:file intoPath:path];
NSLog(#"Downloaded:%#", file);
}
rows of UITableView are reusable, dont set the tag with row index instead us this method
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
id rowObject = [myArray objectAtIndex:indexPath.row];
}