I hope You are well, I've been working a few weeks on iphone and at the moment I have a problem try to open a safari with a url, I have a json file that come a url which is dinamic.
here I leave the code.
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:#"btn.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:#selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.tag = [file objectForKey:#"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:#"name"];
NSString *description = [file objectForKey:#"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender
{
NSString *url = ((UIControl *) sender).tag;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] ];
}
I need to open from the UIButtom an URL without complaint .
Any suggestion or help thank you.
Cheers
Subclass UIButton and add a property to store the URL.
// MyButton.h
#interface MyButton : UIButton {
NSString *urlString_;
}
#property (nonatomic, retain) NSString *urlString;
#end
// MyButton.m
#import "MyButton.h"
#implementation MyButton
#synthesize urlString = urlString_;
- (void)dealloc {
[self setUrlString:nil];
[super dealloc];
}
#end
and then you continue with your code:
#import "MyButton.h"
.
.
.
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:#"btn.png"];
MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:#selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.urlString = [file objectForKey:#"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:#"name"];
NSString *description = [file objectForKey:#"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender {
if ([sender isKindOfClass:[MyButton class]]) {
[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[(MyButton *)sender urlString]]];
}
}
tag is an int type. So you cannot store NSString URL here. You need to store URLs in some other place, may be in a NSMutableArray. Store index i in button's tag and store URL in a NSMutableArray in position i. Then in button handler use the tag as the index to get URL from that NSMutableArray.
And not related with the question, you are not releasing _json NSArray. So you are leaking memory. And also you don't need to test if ([_json count] > 0). Your for loop is already handling that.
Related
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.";
}
I'm trying to build "slot machine" game using UIPickerView. I populate it using UIImageView. Problem is that, random images in picker view disappear after every spin, and randomly shows again. It happens on device with ios 5.1.1, but on device with ios4.2.1 and simulator it works perfectly. Right now I'm using CircularPickerView but before I used UIPickerView and problem was the same.
Here's screenshot: http://axgrzesiek.w.interii.pl/licznik.PNG
GraViewController.h:
#import <UIKit/UIKit.h>
#import "CircularPickerView.h"
#interface GraViewController : UIViewController
<UIPickerViewDataSource, UIPickerViewDelegate> {
CircularPickerView *picker;
UILabel *winLabel;
NSArray *column1;
NSArray *column2;
NSArray *column3;
}
#property(nonatomic, retain) IBOutlet CircularPickerView *picker;
#property(nonatomic, retain) IBOutlet UILabel *winLabel;
#property(nonatomic, retain) NSArray *column1;
#property(nonatomic, retain) NSArray *column2;
#property(nonatomic, retain) NSArray *column3;
-(IBAction)spin;
#end
GraViewController.m:
- (IBAction)spin {
BOOL win = NO;
int numInRow = 1;
int lastVal = -1;
for (int i = 0; i < 3; i++) {
int newValue = arc4random() % [self.column1 count];
if (newValue == lastVal)
numInRow++;
else
numInRow = 1;
lastVal = newValue;
//if (newValue < [self.column1 count] || newValue >= (2 * [self.column1 count]) ) {
//newValue = newValue % [self.column1 count];
//newValue += [self.column1 count];
[self.picker selectRow:newValue inComponent:i animated:YES];
//}
NSLog(#"kol:%d %d",i, newValue);
//[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
}
if (win)
winLabel.text = #"WIN!";
else
winLabel.text = #"";
//[picker reloadAllComponents];
//[self performSelector:#selector(moveIntoPosition) withObject:nil afterDelay:0.5f];
- (void)viewDidLoad {
NSString *title=#"Gra";
[self setTitle:title];
UIImage *seven = [UIImage imageNamed:#"jeden.png"];
UIImage *bar = [UIImage imageNamed:#"dwa.png"];
UIImage *crown = [UIImage imageNamed:#"trzy.png"];
UIImage *cherry = [UIImage imageNamed:#"cztery.png"];
UIImage *lemon = [UIImage imageNamed:#"piec.png"];
UIImage *apple = [UIImage imageNamed:#"szesc.png"];
for (int i = 1; i <= 3; i++) {
UIImageView *sevenView = [[UIImageView alloc] initWithImage:seven];
UIImageView *barView = [[UIImageView alloc] initWithImage:bar];
UIImageView *crownView = [[UIImageView alloc] initWithImage:crown];
UIImageView *cherryView = [[UIImageView alloc] initWithImage:cherry];
UIImageView *lemonView = [[UIImageView alloc] initWithImage:lemon];
UIImageView *appleView = [[UIImageView alloc] initWithImage:apple];
NSArray *imageViewArray = [[NSArray alloc] initWithObjects:
sevenView, barView, crownView, cherryView, lemonView, appleView, nil];
NSString *fieldName = [[NSString alloc] initWithFormat:#"column%d", i];
[self setValue:imageViewArray forKey:fieldName];
//column1=[[NSArray alloc]initWithArray:imageViewArray];
//column2=[[NSArray alloc]initWithArray:imageViewArray];
//column3=[[NSArray alloc]initWithArray:imageViewArray];
[fieldName release];
[imageViewArray release];
[sevenView release];
[barView release];
[crownView release];
[cherryView release];
[lemonView release];
[appleView release];
//[picker selectRow: [self.column1 count] * (48 / 2) inComponent:i-1 animated:NO];
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d", component+1];
NSArray *array = [self valueForKey:arrayName];
[arrayName release];
return [array objectAtIndex:row];
}
I think the problem might be in the way you're reusing views for your picker - you should not cache UIImageViews yourself (probably UIPickerView tries to use the same UIImageView in multiple places, so one of those places stays unoccupied).
Correct way will be to store UIImage instances and fill UIImageView that may be cached by picker. Boilerplate code (not tested):
- (void) viewDidLoad{
...
Here cache UIImages, not UIImageViews
...
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d", component+1];
NSArray *array = [self valueForKey:arrayName];
[arrayName release];
UIImage *image = [array objectAtIndex:row];
if (!view){
view = [[[UIImageView alloc] init] autorelease];
}
[(UIImageView*)view setImage:image];
return view;
}
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)];
}
}
}
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.
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;
}