specific title for each button in UIScrollView - objective-c

I have an UIWebView page with one UIScrollView, inside of my UIScrollView I have UIImage and buttons
I want to set specific title for each button from my xml file, Would you please give me some hint for implementing this?
rightnow I can get the first name from xml but it"s set for all
my scrollView with Button and images:
const NSUInteger kNumImages = 5;
scrollView1.pagingEnabled = YES;
// load all the images
NSUInteger i;
for (i = 1; i<= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.userInteractionEnabled = YES;
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
[scrollView1 addSubview:imageView];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
appDelegate = (testAppDelegate *)[[UIApplication sharedApplication] delegate];
Presentation1Name *aSlide = [appDelegate.books objectAtIndex:0];
NSLog(#" %#", aSlide.slideLabel );
[btn setTitle:[NSString stringWithString:aSlide.slideLabel]
forState:UIControlStateNormal];
btn.frame = rect;
[btn setTag:i];
[btn addTarget:self action:#selector(buttonClick:)
forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:btn];
}
[self layoutScrollImages];
}
for adding title for all button I'm using code
[btn setTitle:[NSString stringWithString:aSlide.slideLabel]
forState:UIControlStateNormal];
but for each button I want to have specific title from xml file
Thanks in advance!
Here is my xml file:
<Presentation label="presentation1">
<slides>
<slide index="0" label="slide1" identifier="Slide1Name" />
<slide index="1" label="something" identifier="Slide2Name" />
</slides>
</Presentation>
Edit:
When I add Presentation1Name *aSlide = [appDelegate.books objectAtIndex:0]; objectAtIndex to i I will get this error
when I add objectAtIndex: i
process terminated * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSPlaceholderString initWithString:]: nil argument'
** First throw call stack:
(0x1c95012 0x10d2e7e 0x1c94deb 0xae97f5 0xae9774 0x3d64 0x4723 0x10e6705 0x1d920 0x1d8b8 0xde671 0xdebcf 0xddd38 0x4d33f 0x4d552 0x2b3aa 0x1ccf8 0x1bf0df9 0x1bf0ad0 0x1c0abf5 0x1c0a962 0x1c3bbb6 0x1c3af44 0x1c3ae1b 0x1bef7e3 0x1bef668 0x1a65c 0x295d 0x2885 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)
and it"s because of
-[NSPlaceholderString initWithString:]: nil argument'
after that I change 5 t0 2 since I have just 2 label in my xml file
const NSUInteger kNumImages= 2;
and also change for (i = 1; i<= kNumImages; i++) to
for (i = 0; i> kNumImages; i++)
but still it"not working correctly
My question is How can I do this
appDelegate.books count should be equal to kNumImages

[btn setTitle:[NSString stringWithFormat:#"MyButton %d", i] forState:UIControlStateNormal];

Store all button names in NSMutableArray and then later use it
For example like this:
NSMutableArray *arrNames = [NSMutableArray alloc]initWithObjects:#"Dog",#"Cat",......,nil]; //fill your array
[btn setTitle:[arrNames objectAtIndex:i] forState:UIControlStateNormal];
Second option is to use #Andrey Chernukha justed in his answer

Related

remove objects from array based on the index

I have array of images here i am doing check and uncheck the images finally i have delete button which are the images i check i need to remove the images from array based on the button selection
here is my code
- (IBAction)delete_btn_touch:(id)sender {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
for(int i=0; i<_GalleryimageArry.count;i++){
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i/2*0.6, 0, 100, 100)];
self.Crossbtn =[[UIButton alloc]initWithFrame:CGRectMake(_imageV.image.size.width/2+80,0,20,20)];
UIImage *btnImage = [UIImage imageNamed:#"unselectimag"];
[self.Crossbtn setImage:btnImage forState:UIControlStateNormal];
_imageV.contentMode = UIViewContentModeScaleAspectFill;
_imageV.image = [_GalleryimageArry objectAtIndex:i];
[_imageV setUserInteractionEnabled:YES];
_imageV.tag = i;
self.Crossbtn.tag =i;
[self.Crossbtn addTarget:self action:#selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapMethod:)];
[_imageV addGestureRecognizer:tap];
[self.imageV addSubview:self.Crossbtn];
[self.imageGalleryscroll addSubview:_imageV];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
self.imageGalleryscroll.delegate = self;
index=0;
self.imageGalleryscroll.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame) * _GalleryimageArry.count/2*0.7, CGRectGetHeight(self.imageGalleryscroll.frame));
[self.imageGalleryscroll setPagingEnabled:YES];
[self.imageGalleryscroll setShowsHorizontalScrollIndicator:NO];
self.imageGalleryscroll.alwaysBounceVertical = NO;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)deleteImage:(UIButton *)sender{
btn = (UIButton *)sender;
self.add_delete_view.hidden =YES;
self.deleteview.hidden=NO;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"unselectimag"]])
{
[btn setImage:[UIImage imageNamed:#"Crossimg"] forState:UIControlStateNormal];
[btn setSelected:YES];
[btn setTag:index];
}
else
{
[btn setImage:[UIImage imageNamed:#"unselectimag"] forState:UIControlStateNormal];
// other statements
self.selectedimages =#"No";
image = [self.GalleryimageArry objectAtIndex:index];
[self.GalleryimageArry addObject:image];
}
NSLog(#"%#", self.GalleryimageArry);
}
- (IBAction)delete_all_img_btn_touch:(id)sender {
// self.view (change it with your button superview)
if (btn.selected) {
[self.GalleryimageArry removeObjectAtIndex:index];
}
//here i need to removeObjectAtIndex:index based on the how many button are selected
}
any one help me to solve this issues
thanks in advance
Use the following code, where you want to clear the back stack of controllers.
-(void)clearStack
{
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeAllObjects];
//[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
}

UIButton is not setting text

I seem to have a problem in my Objective C iOS app where I am creating multiple buttons depending on the amount of objects in an array. I know Swift, so I replicated the logic into Swift, and it worked. Yet in Objective C, I am unable to see the text of the button (after I remove the for loop) or create multiple buttons. For example, I have an array full of three names. I would like to create a button for each name with the title set to the corresponding name. So far, I have this:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i > 10; i++) {
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x > ages.count; x++){
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [[UIColor redColor] CGColor];
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue = button.frame.size.width + 40;
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
- (void)test:(UIButton*)sender{
NSLog(#"Clicked %#", sender.titleLabel.text);
}
#end
If anyone sees anything wrong with this code, please point it out!
Thanks,
Arnav K.
I found four problems (there may be others) that stop this working correctly:
1) The for loop bound when setting up the ages array is incorrect.
2) The for loop bound when creating the buttons is incorrect.
3) You are setting the buttonOutline colour incorrectly.
4) xValue is being updated incorrectly.
Here is the viewDidLoad method after the changes have been made:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) { // UPDATED
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x < ages.count; x++){ // UPDATED
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [UIColor redColor]; // UPDATED
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue += button.frame.size.width + 40; // UPDATED
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
I have marked the four lines I changed with a UPDATED comment so you can compare them to the original.
EDIT
To change the text and text colour use the following:
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitle:[ages objectAtIndex:x] forState:UIControlStateNormal];
and remove this:
button.titleLabel.text = [ages objectAtIndex:x];
You need to do this because you can set different text for the different states of the button and this is all handled automatically for you.

In Objective-C, how can I make this code efficient?

[self.menuBtn1 setImage:[UIImage imageNamed:#"menu1.png"] forState:UIControlStateNormal];
[self.menuBtn2 setImage:[UIImage imageNamed:#"menu2.png"] forState:UIControlStateNormal];
[self.menuBtn3 setImage:[UIImage imageNamed:#"menu3.png"] forState:UIControlStateNormal];
[self.menuBtn4 setImage:[UIImage imageNamed:#"menu4.png"] forState:UIControlStateNormal];
[self.menuBtn5 setImage:[UIImage imageNamed:#"menu5.png"] forState:UIControlStateNormal];
[self.menuBtn6 setImage:[UIImage imageNamed:#"menu6.png"] forState:UIControlStateNormal];
[self.menuBtn7 setImage:[UIImage imageNamed:#"menu7.png"] forState:UIControlStateNormal];
This Code is very inefficient. But I think it can be efficient with forsyntax. However I don't know how can I code self.menuBtn%d with for. In Objective-C, How can I code this?
This access the button properties dynamically so you don't need an array. This only works if the buttons have already been initialized (they are if they're IBOutlets)
NSString *imageName;
NSString *buttonName;
UIImage *image;
for (int i = 1; i < 8; i++) {
//#autoreleasepool {
imageName = [NSString stringWithFormat:#"menu%d", i];
buttonName = [NSString stringWithFormat:#"menuBtn%d", i];
image = [UIImage imageNamed:imageName];
UIButton *button = (UIButton *)[self valueForKey:buttonName];
if (button)
[button setImage:image forState:UIControlStateNormal];
/*
If you needed to scale this to say 1000 images, you can uncomment the first
and last line in the for-loop which will automatically release the variables
each iteration so the memory consumption doesn't spike.
*/
//}
}
One solution might be to set the tag of all your buttons to some value (e.g. 100 + button number), then to try:
for (UIButton *aButton in self.view.subviews)
{
if ((aButton.tag >= 100 and aButton.tag < 107))
[aButton setImage:[UIImage imageNamed:[NSString stringWithFormat:#"menu%d.png",aButton.tag]] forState:UIControlStateNormal];
}
First add the buttons to the array and the use for loop like this:
NSArray *array=[NSArray arrayWithObjects:menuBtn1,menuBtn2,menuBtn3,menuBtn4,menuBtn5,menuBtn6menuBtn7,nil];
int i=1;
for(UIButton *aButton in array){
[aButton setImage:[UIImage imageNamed:[NSString stringWithFormat:#"menu%d.png",i++]] forState:UIControlStateNormal];
}
NSString *menubutton;
NSMutableArray *imagearray = [[NSMutableArray alloc]initWithObjects:#"image1.png",#"image2.png",#"image3.png", nil];
for(int i=0; i<[imagearray count]; i++)
{
menubutton = [NSString stringWithFormat:#"menuBtn%d",i];
UIButton *button = (UIButton *)[self valueForKey:menubutton];
[button setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#",[imagearray objectAtIndex:i]]] forState:UIControlStateNormal];
}

More than 1 image on a subview not loading

I'm trying to add images over a ScrollView. I have the x and y point in a plist file and they are called by an enum.
enum {
kLogoImage = 1,
kNewLogoImage,
};
#implementation
- (void) _setupStaticViews
{
UIButton *image = [UIButton buttonWithType:UIButtonTypeCustom];
[image setBackgroundImage:[UIImage imageNamed:#"logo.png"] forState:UIControlStateNormal];
[image addTarget:self action:#selector(_addContactButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
image.frame = CGRectMake(0.0 ,0.0, 150.0, 150.0);
image.tag = kLogoImage;
[_mapImageView addSubview:image];
_staticViews = #[image];
UIButton *image2 = [UIButton buttonWithType:UIButtonTypeCustom];
[image2 setBackgroundImage:[UIImage imageNamed:#"Time Bakground.png"] forState:UIControlStateNormal];
[image2 addTarget:self action:#selector(_addContactButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
image2.frame = CGRectMake(0.0 ,0.0, 250.0, 150.0);
image2.tag = kNewLogoImage;
[_mapImageView addSubview:image2];
_staticViews = #[image2];
for ( UIView *view in _staticViews ) {
CGPoint point = [self _basePositionForView:view];
CGRect frame = view.frame;
frame.origin = point;
view.frame = frame;
}
}
If I have only image showing, it works fine. But I need to add more than one and adding the second one causes the first one to be at xy point 0,0, and Image2 isn't visible.
How would I go about adding another image?
- (CGPoint) _basePositionForView:(UIView *)view {
NSString *key = [NSString stringWithFormat:#"%d", view.tag];
NSString *stringValue = [_coordinates objectForKey:key];
NSArray *values = [stringValue componentsSeparatedByString:#":"];
if ( [values count] < 2 ) return CGPointZero;
CGPoint result = CGPointMake([[values objectAtIndex:0] floatValue], [[values objectAtIndex:1] floatValue]);
return result;
}
I noticed that you first make
_staticViews = #[image];
and later
_staticViews = #[image2];
Don't you rather mean to have
_staticViews = #[image, image2];
?
You should iterate and change x accordingly in the frame:
for ( int iterator=0; iterator< [[_staticViews subviews] count]; iterator++){
...
current_image.frame = CGRectMake(YOUR_IMG_WIDTH * iterator ,0.0, YOUR_IMG_WIDTH, 150.0);
...}

Why this brings about SIGABRT error?

I have some sources below.
- (void)Button:(UIButton *)button {
NSString *imageName = ((UIButton *)[self.view viewWithTag:button.tag]).titleLabel.text;
}
- (void)viewDidLoad {
NSMutableArray *_array = [[NSMutableArray alloc] init];
NSInteger iCount = [_array count];
for (i = 0; iCount > i; i++) {
UIButton *btn = [[UIButton alloc] init];
btn.titleLabel.text = [[_array objectAtIndex:i] objectForKey:#"FILE"];
btn.tag = i;
[btn addTarget:self action:#selector(Button:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[btn release];
}
When I access Button method with 0 index tag, I get SIGABRT error.
What can I do ?
Read your console output properly, by default every view has the tag '0', so it can be crashed because it is taking some other view besides of uibutton, and may be that view don't not have the titleLabel property.Because it is the property of UIButton.