How to show image loaded from a url on a button? - iphone

Here is an example :
Show multi image on multi button and show on scrollview
(void)viewDidLoad
{
[super viewDidLoad];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
InitData *inData=[[InitData alloc]init];
scrollview.delegate=self;
scrollview.scrollEnabled = YES;
int scrollWidth = 120;
scrollview.contentSize = CGSizeMake(scrollWidth,100);
int xOffset = 0;
//imageView.image = [UIImage imageNamed:[imagesName objectAtIndex:0]];
//Test
NSURL *url=[NSURL URLWithString:#"....."];
NSData *jsonData=[NSData dataWithContentsOfURL:url];
if (jsonData !=nil)
{
NSError *error=nil;
id result=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error ==nil)
{
NSLog(#"%#",result);
// NSMutableArray *ArImg = nil;
NSArray* rus=[result objectForKey:#"RespOBJ"];
for (int index = 0; index < rus.count ; index++)
{
NSMutableDictionary* final=[rus objectAtIndex:index];
[inData setId:(int)[final objectForKey:#"Id"]];
[inData setTum:[final objectForKey:#"TumbImage"]];
[inData setImage:[final objectForKey:#"Image"]];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:[inData getImage]] forState:(UIControlStateNormal)];
//[btn setImage:[UIImage imageWithData:jsonData] forState:(UIControlStateNormal)];
[btn setTag:index];
btn.bounds = CGRectMake(10, 10, 50, 50);
btn.frame = CGRectMake(5+xOffset, 0, 160, 70);
scrollview.contentSize = CGSizeMake(scrollWidth+xOffset,70);
NSLog(#"%#",[inData getId]);
NSLog(#"%#",[inData getImage]);
NSLog(#"%#",[inData getTum]);
[btn addTarget:self
action: #selector(btnclick:)
forControlEvents: UIControlEventTouchDown];
[scrollview addSubview:btn];
xOffset += 170;
}

The problem with your code is that you are not loading anything. I assume you want to download the image from the Internet and then display it on the scrollview. To do so, you have to use a NSURLRequest and a NSURLConnection.
Have a look at Apple's documentation https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html and https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
You might also like this question on how to load data asynchronously Object-c/iOS :How to use ASynchronous to get a data from URL?

Related

Picture taken form iphone real device that images displaying in thumbnail is taking too long in iphone

I am new to i phone programming.I have store images in array then using below code i am displaying images in thumbnail its working very fast.If same think i have store images in database and retrieving images and storing in array then using below code i am displaying images in thumbnail its taking too long to displaying thumbnail images.
arrayz = [NSMutableArray arrayWithObjects:[UIImage imageNamed:#"image3.jpg"],
[UIImage imageNamed:#"image4.jpg"],
[UIImage imageNamed:#"image5.jpg"],
[UIImage imageNamed:#"image3.jpg"],
[UIImage imageNamed:#"image5.jpg"],
[UIImage imageNamed:#"image4.jpg"],
[UIImage imageNamed:#"image2.jpg"],
[UIImage imageNamed:#"image3.jpg"],
[UIImage imageNamed:#"image2.jpg"],
[UIImage imageNamed:#"image5.jpg"],
nil];
NSLog(#"%i" , [arrayz count]);
NSLog(#"%#",arrayz);
myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 840.0)];
myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(320.0, 840.0);
myScrollView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:myScrollView];
float horizontal = 8.0;
float vertical = 8.0;
for(int i=0; i<[arrayz count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage1 = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage1 setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage1 setTag:i];
[buttonImage1 setImage:[arrayz objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage1 addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonImage1 setImage:[UIImage imageNamed:#"Overlay.png"] forState:UIControlStateSelected];
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[buttonImage setImage:[arrayz objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonImage setImage:[UIImage imageNamed:#"Overlay.png"] forState:UIControlStateSelected];
// UIImageView *imageee=[[UIImageView alloc]initWithFrame:CGRectMake(10,10, 80,80)];
// [buttonImage setImage:[UIImage imageNamed:#"check.jpg"]];
// [buttonImage setImage:imageee forState:UIControlStateSelected];
// [buttonImage setImage:button.currentImage forState:UIControlStateNormal];
[myScrollView addSubview:buttonImage1];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
[myScrollView setContentSize:CGSizeMake(320.0, vertical + 78.0)];
}
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
// UIBarButtonItem *done =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStyleDone target:self action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = done;
below code using database i am storing images in array then i am displaying images in thumbnail.its taking too long to display the images in thumbnail.
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
array=[[NSMutableArray alloc]init];
array1=[[NSMutableArray alloc]init];
// array2=[[NSMutableArray alloc]init];
// Build the path to the database file
databasePath = [docsDir stringByAppendingPathComponent: #"Taukydataaa.db"];
// NSLog(#"%#",databasePath);
NSFileManager *fn=[NSFileManager defaultManager];
NSError *error;
BOOL success=[fn fileExistsAtPath:databasePath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Taukydataaa.db"];
success = [fn copyItemAtPath:defaultDBPath toPath:databasePath error:&error];
}
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"select * from path "];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString* email_idField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,1)];
// NSLog(#"%#",email_idField);
NSString* email_idField1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,0)];
// NSLog(#"%#",email_idField1);
// NSString *email_idField2 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,2)];
NSLog(#"ASlma");
NSLog(#"%#",email_idField1);
[array addObject:email_idField];
[array1 addObject:email_idField1];
NSLog(#"%#",array);
NSLog(#"%#",array1);
// [array1 addObject:email_idField1];
// [array2 addObject:email_idField2];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
blaukypath =[[NSMutableArray alloc]init];
for (NSString* path in array)
{
[blaukypath addObject:[UIImage imageWithContentsOfFile:path]];
NSLog(#"%#",path);
}
NSLog(#"%#",blaukypath1);
myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 840.0)];
myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(320.0, 840.0);
myScrollView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:myScrollView];
float horizontal = 8.0;
float vertical = 8.0;
for(int i=0; i<[blaukypath count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage1 = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage1 setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage1 setTag:i];
[buttonImage1 setImage:[blaukypath objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage1 addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonImage1 setImage:[UIImage imageNamed:#"Overlay.png"] forState:UIControlStateSelected];
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[buttonImage setImage:[blaukypath objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonImage setImage:[UIImage imageNamed:#"Overlay.png"] forState:UIControlStateSelected];
// UIImageView *imageee=[[UIImageView alloc]initWithFrame:CGRectMake(10,10, 80,80)];
// [buttonImage setImage:[UIImage imageNamed:#"check.jpg"]];
// [buttonImage setImage:imageee forState:UIControlStateSelected];
// [buttonImage setImage:button.currentImage forState:UIControlStateNormal];
[myScrollView addSubview:buttonImage1];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
[myScrollView setContentSize:CGSizeMake(320.0, vertical + 78.0)];
}
I think problem is not with database.What main think is if i take images from i phone real device that images taking too long to display in thumbnail.If i take some images and store in array that images displaying in thumbnail its working very fast..
Can any body tell me How to slove this.
Thanks
Aslam
Real images will have more size, so better you resize them before use. Try this one
UIImage *originalImage = your orginal Image
CGSize destinationSize = CGSizeMake(100, 120);// your destination thumbnail size
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

How to Access Particular view of a pageControl viewController?

Hi I m creating a project where multiple Images Loading from Server With some like Count and Comment Count and a Button to like the image. I m showing the individual Images With using a Slider Controller like PageControl.
this is My code for Showing the View
-(UIView*)reloadView:(DPSliderView *)sliderView viewAtIndex:(NSUInteger)idx
{
_loading_view.hidden=TRUE;
if (idx < [photos count]) {
NSDictionary *item = [photos objectAtIndex:idx];
PhotoView *v = [[PhotoView alloc] init];
v.photoIndex = idx;
v.imageView.imageURL = [DPAPI urlForPhoto:item[#"photo_220x220"]];
NSString *placename1 = [item valueForKeyPath:#"spotting.item.name"];
NSString *firstCapChar1 = [[placename1 substringToIndex:1] capitalizedString];
NSString *cappedString1 = [placename1 stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar1];
v.spotNameLabel.text = cappedString1;
NSString *placename = [item valueForKeyPath:#"spotting.place.name"];
NSString *firstCapChar = [[placename substringToIndex:1] capitalizedString];
NSString *cappedString = [placename stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSString *place1=[NSString stringWithFormat:#"%#",cappedString];
NSString *address=[NSString stringWithFormat:#"%#",[item valueForKeyPath:#"spotting.place.address"]];
NSString *location_str3 = [NSString stringWithFormat:#"# %#, %#",place1,address];
int cap_len=[place1 length];
int address_lenth=[address length];
ZMutableAttributedString *str = [[ZMutableAttributedString alloc] initWithString:location_str3
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12],
ZFontAttributeName,
nil]];
[str addAttribute:ZFontAttributeName value:[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12] range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:241/255.0f green:73.0/255.0f blue:2.0/255.0f alpha:1.0]range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:128.0/255.0f green:121.0/255.0f blue:98.0/255.0f alpha:1.0]range:NSMakeRange(cap_len+4, address_lenth)];
v.placefontlabel.zAttributedText=str;
v.likesCountLabel.text = [NSString stringWithFormat:#"%i", [item[#"likes_count"] intValue]];
if ([_device_lang_str isEqualToString:#"es"])
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Vistas", nil), [item[#"sightings_count"] intValue]];
}
else
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Sightings", nil), [item[#"sightings_count"] intValue]];
}
if ([nolocationstr isEqualToString:#"YES"])
{
v.distanceLabel.text =[NSString stringWithFormat:#"%.2f km", [item[#"distance"] floatValue]];
}
else
{
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[[item valueForKeyPath:#"spotting.place.lat"]floatValue] longitude:[[item valueForKeyPath:#"spotting.place.lng"] floatValue]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[_explore_lat_str floatValue] longitude:[_explore_lng_str floatValue]];
NSString *lat_laong=[NSString stringWithFormat:#"%f",[location1 distanceFromLocation:location2]];
int km=[lat_laong floatValue]*0.001;
NSString *distancestr=[NSString stringWithFormat:#"%d km",km];
float dist=[distancestr floatValue];
v.distanceLabel.text = [NSString stringWithFormat:#"%.2f km", dist];
}
if (![item[#"likes"] boolValue]) {
v.likeButton.enabled = YES;
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new.png"] forState:UIControlStateNormal];
[v.likeButton addTarget:self action:#selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new1.png"] forState:UIControlStateNormal];
}
NSArray *guides = item[#"guides"];
if ([guides count] > 0) {
NSString *guideType = [[guides objectAtIndex:0] valueForKey:#"type"];
UIImage *guidesIcon = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png", guideType]];
v.guideButton.hidden = NO;
v.guideButton.tag = idx;
[v.guideButton setImage:guidesIcon forState:UIControlStateNormal];
[v.guideButton addTarget:self action:#selector(guideAction:) forControlEvents:UIControlEventTouchUpInside];
}
v.shareButton.tag = idx;
[v.shareButton addTarget:self action:#selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(photoTapGesture:)];
[v addGestureRecognizer:tapGesture];
[tapGesture release];
return [v autorelease];
} else {
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sc_img.png"]];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(CGRectGetMidX(iv.bounds), 110);
[indicator startAnimating];
[iv addSubview:indicator];
[indicator release];
return [iv autorelease];
}
}
Now My question is :
If i will Click on Like Button , Then i have to change the button image as well as like count. I can able to Change the Button Image By This Method
[sender setImage:[UIImage ImageNamed:#"image.png"]];
But How can I change the Like count of the Label ? How can i access the Particular label of the View ? I have assigned the tag But , I dont know how to assign it.I dont want to Reload Whole Slider as the Photo are loading from Network (Remote Server) . Thanks for your Time.
Just keep a reference to the label and update that.
// #interface
#property (nonatomic, strong) UILabel *myLabel;
// #implementation
_myLabel.text = #"Whatever.";
If you have multiple labels, set the tags when you create your views
newView.tag = sequenceNumber +100;
And then update
-(void)updateLabelWithTag:(NSInteger)tag {
UILabel *label = (UILabel*) [self.scrollView viewWithTag:tag];
label.text = #"Whatever.";
}

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

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.

How to Importing image from server and arrange it in a view

I need to get array of images that have to call from server and arrange that in an order.But while executing below code i can't get it...Guidance please...
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
NSURL *url = [NSArray arrayWithObjects:[NSURL URLWithString:
#"http://images.wikia.com/marvelmovies/images/5/5e/The-hulk-2003.jpg"],
[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],
[NSURL URLWithString:#"http://challenge.roadef.org/2012/img/google_logo.jpg"],
[NSURL URLWithString:#"http://addyosmani.com/blog/wp-content/uploads/2012/03/Google-doodle-of-Richard-007.jpg"],
[NSURL URLWithString:#"http://techcitement.com/admin/wp-content/uploads/2012/06/apple-vs-google_2.jpg"],
[NSURL URLWithString:#"http://www.andymangels.com/images/IronMan_9_wallpaper.jpg"],
[NSURL URLWithString:#"http://sequelnews.com/wp-content/uploads/2011/11/iphone_5.jpg"],Nil];
/*
int i=0;
int cord_x=0;
int cord_y=30;
int cont=0;
for (i = 0; i < [(NSArray*)url count]; i++) {
cont=cont+1;
if (cont > 3) {
cord_x=0;
cord_y=cord_y+110;
cont=1;
}*/
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*)[(NSArray*)url objectAtIndex:index]]];
//cord_x=cord_x+110;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 200.0f, 200.0f);
[button setImage:(UIImage*)[image objectAtIndex:index] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
//}
now i need to place button image and image from server...
You can try to use NSURLConnection to download images asynchronous which will make your UI much more responsive. Just setup separate connection for each image and update images on the buttons in delegate method - connectionDidFinishLoading. It will also help you to track downloading errors (e.g. timeouts etc.).
Here is a great example with downloads images for table - you can find there a lot of help for your case:
http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html
int row = 0;
int column = 0;
for(int i = 0; i < url.count; ++i) {
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*) [(NSArray*)url objectAtIndex:i]]];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+16, row*90, 80, 80);
[button setImage:image forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.view addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
NSMutableArray *arrayList=[[NSMutableArray alloc] initWithObjects:#"www.xxx.com/imag.jpg",#"www.xxx.com/img1.jpg",nil];
for(int i=0; i<[arrayList count]; i++)
{
NSURL *url = [NSURL URLWithString:[arrayList ObjetAtIndex:i]];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *img=[UIImage imageWithData:data]; // Here is your image
}
NSURL *url = [NSArray arrayWithObjects:[NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],Nil];
int i=0;
int cord_x=0;
int cord_y=30;
int cont=0;
for (i = 0; i < [(NSArray*)url count]; i++)
{
cont=cont+1;
if (cont > 3)
{
cord_x=0;
cord_y=cord_y+110;
cont=1;
}
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*)[(NSArray*)url objectAtIndex:i]]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cord_x, cord_y, 100, 100)];
[imageView setImage:image];
[self.view addSubview:imageView];
cord_x=cord_x+110;
}