how to create action multiple dynamic buttons in ios? - ios

i am creating multiple buttons dynamically now i want to set action for each buttons.
when i press buttons its show result on next screen in my application .
i am using FMDB library to read data from database.(read database according to id on buttons press). i know how to read database from database . i want only fetch data on buttons press and display that
data on table view .how to create action for each buttons?
this my buttons code :
-(void)DynamicButton:(NSMutableArray*)objectName
{
for(UIView *view in [scrollView subviews])
{
[view removeFromSuperview];
}
int yPossion = 100, xPossion = 44; int temp = 0;
for (int i = 0; i<[objectName count]; i++)
{
SMSCategory *cat = [objectName objectAtIndex:i];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTag:i];
[aButton setTranslatesAutoresizingMaskIntoConstraints:YES];
[aButton setBackgroundColor:[UIColor blackColor]];
[aButton setBackgroundImage:[UIImage imageNamed:#"icon-menu.png"]
forState:UIControlStateNormal];
[aButton setTitle:[NSString stringWithFormat:#"%d",i]
forState:UIControlStateNormal];
[aButton setFrame:CGRectMake(xPossion, yPossion, 70, 60)];
aButton.highlighted=YES;
[scrollView addSubview:aButton];
;
xPossion += aButton.frame.size.width+35;
temp++;
if (temp==3)
{
yPossion = aButton.frame.origin.y+aButton.frame.size.height+20;
temp = 0;
xPossion = 44;
yPossion += aButton.frame.size.width-15;
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width ,yPossion-
50)];
}
UILabel *label = [[UILabel alloc] init];
[label setTranslatesAutoresizingMaskIntoConstraints:YES];
[label setText:cat.Name];
[label setTextColor:[UIColor blackColor]];
label.font = [UIFont systemFontOfSize:12];
[label sizeToFit];
[label setFrame:CGRectMake(4, 44, 70, 60)];
[scrollView addSubview:label];
[aButton addSubview:label];
}
}

UIButton *test = [self buttonWithTitle:#"test" target:self selector:#selector(testDoit) frame:CGRectMake(self.view.center.x-50, 270.0, 100.0, 50.0) : 12];
- (UIButton *)buttonWithTitle:(NSString *)title target:(id)target selector:(SEL)inSelector frame:(CGRect)frame :(int)fontSize{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:frame];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont boldSystemFontOfSize:fontSize];
button.userInteractionEnabled = YES;
button.titleLabel.textAlignment = UITextAlignmentCenter;
button.titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
button.titleLabel.shadowOffset = CGSizeMake (1.0, 0.0);
button.titleLabel.textColor = [UIColor blackColor];
button.showsTouchWhenHighlighted = YES;
button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleRightMargin|
UIViewAutoresizingFlexibleTopMargin|
UIViewAutoresizingFlexibleHeight|
UIViewAutoresizingFlexibleBottomMargin;
[button addTarget:self action:inSelector forControlEvents:UIControlEventTouchUpInside];
//[button autorelease];
return button;
}

Related

App crashes with received memory Exception in ARC while scrolling the scrollview with out using images

I am Using UIScrollview and adding subView to display the message. While scrolling it gives received memory exception. I am struggling to find this from 15 days. Please help me to solve this.
To display I am loading 5 messages first time. After scrolling adding the subView according to array count.If it is subView is increased according the message length.If it is long messages,It crashes with received memory exception.
This is my code
-(void)createView:(float)yAxis
{
// NSLog(#"Create view %f",yAxis);
for (UIView * view in backgroundScroll.subviews) {
if (view.tag == 15) {
[view removeFromSuperview];
}
}
for(int i=0;i<[pageMessageArray count];i++)
{
UIView *backgrounf_View=[self messageChildElements:yAxis :i];
[del.msglistViewArray addObject:backgrounf_View];
UIView *backgrounf_View1= [del.msglistViewArray objectAtIndex:i];
[backgroundScroll addSubview:backgrounf_View1];
yAxis=yAxis+oldY_Axis+65;
}
CGRect contentRect = CGRectZero;
for (UIView *view in backgroundScroll.subviews)
{
contentRect = CGRectUnion(contentRect, view.frame);
}
//UIView *backgrounf_View1= [del.msglistViewArray objectAtIndex:i];
backgroundScroll.contentSize = CGSizeMake(backgroundScroll.frame.size.width, yAxis-10);
lblPermenentmessage.frame=CGRectMake(30, contentRect.size.height+20,800, 50);
//LastMessageYaxis=contentRect.size.height+20;
lblPermenentmessage.text=#"Messages are displayed for 24-48 hours and automatically deleted permanently.";
}
-(UIView *)messageChildElements:(float)yAxis :(int)index
{
// NSLog(#"Create view %f",yAxis);
communityObject *objMessage=[del.messageArray objectAtIndex:index];
UIView *backgrounf_View=nil;
UITextView *txt_Message=nil;
UIButton *btnURL =nil;
UIButton *btnAttachment=nil;
UIButton *btnDate=nil;
UIButton *btnSendBy=nil;
UIButton *btnAttachmentName=nil;
UIButton *btnSendTo=nil;
NSString *labelText = objMessage.Message;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:8];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
CGFloat height=[self getNewsize:objMessage.Message :backgroundScroll.frame.size.width-30];
backgrounf_View=[[UIView alloc]initWithFrame:CGRectMake(26,yAxis,backgroundScroll.frame.size.width-30,height)];
if([objMessage.inorout isEqualToString:#"out"])
{
//ye
[backgrounf_View setBackgroundColor:[UIColor colorWithRed:251/255.0f green:247/255.0f blue:193/255.0f alpha:1.0f]];
[[backgrounf_View layer] setBorderWidth:1.0f];
[[backgrounf_View layer] setBorderColor:[UIColor colorWithRed:236/255.0f green:237/255.0f blue:178/255.0f alpha:1.0f].CGColor];
}
else
{
//[cell.lblName addTarget:self action:#selector(replayClick:) forControlEvents:UIControlEventTouchUpInside];
[backgrounf_View setBackgroundColor:[UIColor colorWithRed:251/255.0f green:215/255.0f blue:245/255.0f alpha:1.0f]];
[[backgrounf_View layer] setBorderWidth:1.0f];
[[backgrounf_View layer] setBorderColor:[UIColor colorWithRed:226/255.0f green:188/255.0f blue:218/255.0f alpha:1.0f].CGColor];
}
// backgrounf_View.autoresizingMask=UIViewAutoresizingFlexibleWidth;
backgrounf_View.layer.cornerRadius=10;
//backgrounf_View.tag=15;
backgrounf_View.clipsToBounds=YES;
backgrounf_View.tag=objMessage.indexValue;
txt_Message = [[UITextView alloc] initWithFrame:CGRectMake(12, 6, backgroundScroll.frame.size.width-40, height)];
txt_Message.backgroundColor=[UIColor redColor];
[txt_Message setScrollEnabled:NO];
[txt_Message setUserInteractionEnabled:NO];
[txt_Message setBackgroundColor:[UIColor clearColor]];
//txt_Message.autoresizingMask=UIViewAutoresizingFlexibleWidth;
txt_Message.attributedText=attributedString;
//[txt_Message sizeToFit];
if([del.device isEqualToString:#"iphone"])
{
[txt_Message setFont:[UIFont fontWithName:#"Arial" size:17]];
}
else
{
[txt_Message setFont:[UIFont fontWithName:#"Arial" size:21]];
}
[backgrounf_View addSubview:txt_Message];
oldY_Axis=height+20;
if (objMessage.Link.length>0)
{
btnURL = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnURL.frame = CGRectMake(11,height,backgroundScroll.frame.size.width-100,40);
[btnURL setTitle:objMessage.Link forState:UIControlStateNormal];
btnURL.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btnURL.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
// btnURL.backgroundColor=[UIColor redColor];
btnURL.tag=objMessage.indexValue;
btnURL.titleLabel.lineBreakMode=UILineBreakModeCharacterWrap;
btnURL.titleLabel.numberOfLines=2;
btnURL.titleLabel.font=[UIFont fontWithName:#"Arial" size:20];
btnURL.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[btnURL setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backgrounf_View addSubview:btnURL];
oldY_Axis=height+btnURL.frame.size.height+20;
}
if (objMessage.Filename.length>0)
{
btnAttachment= [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnAttachment.frame = CGRectMake(11, oldY_Axis,40, 40);
btnAttachment.tag=objMessage.indexValue;
UIImage *buttonattachment=[UIImage imageNamed:#"attach.png"];
[btnAttachment setBackgroundImage:buttonattachment forState:UIControlStateNormal];
btnAttachment.userInteractionEnabled=YES;
btnAttachmentName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnAttachmentName.frame = CGRectMake(47,oldY_Axis+5,backgroundScroll.frame.size.width-150,60);
[btnAttachmentName setTitle:objMessage.Filename forState:UIControlStateNormal];
btnAttachmentName.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btnAttachmentName.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btnAttachmentName.tag=objMessage.indexValue;
btnAttachmentName.titleLabel.font=[UIFont fontWithName:#"Arial" size:20];
btnAttachmentName.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[btnAttachmentName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backgrounf_View addSubview:btnAttachment];
[backgrounf_View addSubview:btnAttachmentName];
oldY_Axis=oldY_Axis+btnAttachment.frame.size.height+30;
}
btnDate = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnDate.frame = CGRectMake(11,oldY_Axis,130,30);
[btnDate setTitle:[NSString stringWithFormat:#"%#:",objMessage.Date] forState:UIControlStateNormal];
btnDate.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btnDate.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btnDate.tag=objMessage.indexValue;
btnDate.titleLabel.font=[UIFont fontWithName:#"Arial" size:15];
btnDate.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[btnDate setTitleColor:[UIColor colorWithRed:70/255.0f green:70/255.0f blue:70/255.0f alpha:1.0f] forState:UIControlStateNormal];
[backgrounf_View addSubview:btnDate];
btnSendBy = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnSendBy.frame = CGRectMake(127,oldY_Axis,backgroundScroll.frame.size.width-50,200);
[btnSendBy setTitle:objMessage.senderPerson forState:UIControlStateNormal];
btnSendBy.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btnSendBy.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btnSendBy.tag=objMessage.indexValue;
// btnURL.backgroundColor=[UIColor redColor];
//btnSendBy.titleLabel.lineBreakMode=UILineBreakModeCharacterWrap;
btnSendBy.titleLabel.font=[UIFont fontWithName:#"Arial" size:15];
btnSendBy.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[btnSendBy setTitleColor:[UIColor colorWithRed:70/255.0f green:70/255.0f blue:70/255.0f alpha:1.0f] forState:UIControlStateNormal];
[backgrounf_View addSubview:btnSendBy];
btnSendTo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnSendTo.frame = CGRectMake(11,oldY_Axis+25,backgroundScroll.frame.size.width-50,200);
[btnSendTo setTitle:objMessage.senderPerson forState:UIControlStateNormal];
btnSendTo.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btnSendTo.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
// btnURL.backgroundColor=[UIColor redColor];
//btnSendBy.titleLabel.lineBreakMode=UILineBreakModeCharacterWrap;
btnSendTo.titleLabel.font=[UIFont fontWithName:#"Arial" size:15];
btnSendTo.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[btnSendTo setTitleColor:[UIColor colorWithRed:70/255.0f green:70/255.0f blue:70/255.0f alpha:1.0f] forState:UIControlStateNormal];
[backgrounf_View addSubview:btnSendTo];
NSString *communityName=#"";
if([del.communityId isEqualToString:#"none"])
{
communityName=objMessage.Community;
communityName=[NSString stringWithFormat:#"%#: ",objMessage.Community];
}
//NSLog(#"Group type %# and %#",objMessage.groupType,del.communityId);
if([objMessage.groupType isEqualToString:#"Personal"])
{
[btnSendTo setTitle:[NSString stringWithFormat:#"%#%#",communityName,objMessage.Person] forState: UIControlStateNormal];
}
else if([objMessage.groupType isEqualToString:#"Everyone"])
{
[btnSendTo setTitle:[NSString stringWithFormat:#"%#%#",communityName,#"Everyone"] forState: UIControlStateNormal];
}
else
{
[btnSendTo setTitle:[NSString stringWithFormat:#"%#%#",communityName,objMessage.GroupName] forState: UIControlStateNormal];
}
[btnURL addTarget:self action:#selector(getLink:) forControlEvents:UIControlEventTouchUpInside];
[btnAttachmentName addTarget:self action:#selector(fileDowload:) forControlEvents:UIControlEventTouchUpInside];
[btnAttachment addTarget:self action:#selector(fileDowload:) forControlEvents:UIControlEventTouchUpInside];
backgrounf_View.frame=CGRectMake(24,yAxis,backgroundScroll.frame.size.width-30,oldY_Axis+55);
LastMessageYaxis=backgrounf_View.frame.origin.y+backgrounf_View.frame.size.height+10;
del.RefreshValue=0;
LastValue=index;
communityObject *com=[[communityObject alloc]init];
com.MessageId=nil;
com.Date=nil;
com.Message=nil;
com.Link=nil;
com.Attachment=nil;
com.Filename=nil;
com.attachmentType=nil;
com.imageSize=nil;
com.groupType=nil;
com.Person=nil;
com.GroupName=nil;
com.senderPerson=nil;
com.Community=nil;
com.inorout=nil;
return backgrounf_View;
}
Sceenshot is added please check.
This bit looks like a mutation of array while enumerating it:
for (UIView * view in backgroundScroll.subviews) {
if (view.tag == 15) {
[view removeFromSuperview];
}
}
There is no wonder why the array doesn't like it. I would crash too :)
BTW: That part where it is storing indexes of array in view's tag seems very wrong.

how to set different image for dynamic buttons in ios?

I am creating 20 buttons dynamically in my apps project now i want to set images for each button like not same image will be different for each buttons. I try lot of solution but not getting proper result. I am implemented following code for this......
int yPossion = 150, xPossion = 44; int temp = 0;
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
[self.view addSubview:scrollView];
for (int i = 0; i < [objectName count]; i++) {
SMSCat1 *cat = [objectName objectAtIndex:i];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTranslatesAutoresizingMaskIntoConstraints:YES];
//Label Dynamic Code
UILabel *label = [[UILabel alloc] init];
[label setText:cat.Name];
[label setTextColor:[UIColor brownColor]];
label.font = [UIFont systemFontOfSize:12];
[label sizeToFit];
[label setFrame:CGRectMake(5, 44, 70, 60)];
[scrollView addSubview:label];
[aButton addSubview:label];
[aButton setBackgroundColor:[UIColor blackColor]];
[aButton setBackgroundImage:[UIImage imageNamed:#"icon-menu.png"]
forState:UIControlStateNormal];
[aButton setTitle:[NSString stringWithFormat:#"%d", i] forState:UIControlStateNormal];
[aButton setFrame:CGRectMake(xPossion, yPossion, 70, 60)];
aButton.highlighted = YES;
[scrollView addSubview:aButton];
xPossion += aButton.frame.size.width + 35;
temp++;
if (temp == 3) {
yPossion = aButton.frame.origin.y + aButton.frame.size.height + 20;
temp = 0;
xPossion = 44;
yPossion += aButton.frame.size.width - 15;
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, yPossion - 50)];
}
}
}
Please help me to complete that task. I added 20 images on image folder but how to set that image for each buttons its like (can i use settag for this).
Don't be afraid to ask if you are new. Looking at other peoples code and learning is how we all get better at what we do. You can find the answer to your question here - how to set auto layout for dynamically created buttons? Hope this helps you

drag drop issue in buttons

i have created a few butttons via code
for(int i=0;i<2;i++)
{
UIButton *btn_pin = [[UIButton alloc] initWithFrame:CGRectMake(100*i,100*i, 20, 20)];
[btn_pin setBackgroundColor:[self colorFromHexString:#"5DBBAB"]];
[btn_pin setTitle:[NSString stringWithFormat:#"%d",[arr_product count]+1] forState:UIControlStateNormal];
[btn_pin.titleLabel setFont:[UIFont fontWithName:#"ProximaNova-Regular" size:10.0]];
btn_pin.layer.cornerRadius = 10.0;
btn_pin.layer.masksToBounds = YES;
btn_pin.layer.borderColor = [UIColor whiteColor].CGColor;
btn_pin.layer.borderWidth = 1.0;
btn_pin.userInteractionEnabled = TRUE;
btn_pin.titleEdgeInsets = UIEdgeInsetsMake(2, 0, 0, 0);
[btn_pin.layer setBorderColor:[UIColor whiteColor].CGColor];
[btn_pin addTarget:self action:#selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDown];
[btn_pin addTarget:self action:#selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[img_main addSubview:btn_pin];
[tbl_product reloadData];
}
and now i want to move those buttons aroudn via drag , i have created a drag drop already but how do i get the reference of this button .
in your loop:
btn_pin.tag = i;
and in imageMoved :
UIButton *btn_pin = (UIButton *)sender;
int refIndex = btn_pin.tag;

Delete button on UIWebView

Im getting touch location coordinates from UIWebView and displays the button with coordinates. It's working with coordinates match. So, i need to increase the button. I didn't use Array for button. When i delete particular button from UIWebView it delete all the button. Shall i use NSMutableArray?. Here x & y is the touch point coordinates in float value
if(x && y){
NSLog(#"x is %f",x);
NSLog(#"y is %f",y);
button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 addTarget:self
action:#selector(click1:)
forControlEvents:UIControlEventTouchDown];
[button1 setTitle:#"click" forState:UIControlStateNormal];
button1.frame = CGRectMake(x, y, 30.0, 20.0);
// [btnArray addObject:button1];
button1.tag = gTag;
gTag++;
[wbCont.scrollView addSubview:button1];
}
Delete the button:
-(void)recycle:(id)sender{
for(int i=1;i<gTag;i++){
[[wbCont.scrollView viewWithTag:i] removeFromSuperview];
}
-(void)click1:(id)sender{
UIButton *mainBtn = (UIButton *)sender;
int mainTag = mainBtn.tag;
txtview = [[UITextView alloc]initWithFrame:CGRectMake(0,0,320,568)];
txtview.font = [UIFont fontWithName:#"Helvetica" size:12];
txtview.font = [UIFont boldSystemFontOfSize:12];
txtview.backgroundColor = [UIColor whiteColor];
txtview.scrollEnabled = YES;
txtview.pagingEnabled = YES;
txtview.editable = YES;
txtview.tag = mainTag*1000;
for(int i=0; i<[textArray count];i++){
txtview.text=[textArray objectAtIndex:i];
}
[self.view addSubview:txtview];
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(done:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Done" forState:UIControlStateNormal];
button.frame = CGRectMake(240.0, 20.0, 60.0, 40.0);
[txtview addSubview:button];
recyclebtn=[UIButton buttonWithType:UIButtonTypeCustom];
recyclebtn.tag = mainBtn.tag;
[recyclebtn addTarget:self action:#selector(recycle:) forControlEvents:UIControlEventTouchDown];
[recyclebtn setImage:[UIImage imageNamed:#"recycle.png"] forState:UIControlStateNormal];
recyclebtn.frame=CGRectMake(0, 10, 30, 30);
[txtview addSubview:recyclebtn];
}
-(void)recycle:(id)sender {
UIButton *btnTemp = (UIButton *)sender;
[[wbCont.scrollView viewWithTag:btnTemp.tag] removeFromSuperview];
int txtTag = btnTemp.tag*1000;
[[self.view viewWithTag: txtTag] removeFromSuperview];
}

Making series of buttons into an array ios

I have about 10-12 buttons that I'm adding to my scrollview. How can I make these into an array of buttons so that I can simplify the code? As of right now my code(only first three buttons are shown) is as follows:
UIButton *redButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
redButton.frame = CGRectMake(0, 0, 50, 30);
redButton.tag = 2;
[redButton setTitle:#"red" forState:UIControlStateNormal];
redButton.backgroundColor = [UIColor redColor];
[redButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[redButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.scollView addSubview:redButton];
UIButton *blueButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
blueButton.frame = CGRectMake(70, 0, 50, 30);
blueButton.tag = 3;
[blueButton setTitle:#"blue" forState:UIControlStateNormal];
blueButton.backgroundColor = [UIColor blueColor];
[blueButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[blueButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.scollView addSubview:blueButton];
UIButton *greenButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
greenButton.frame = CGRectMake(140, 0, 50, 30);
greenButton.tag = 5 ;
[greenButton setTitle:#"green" forState:UIControlStateNormal];
greenButton.backgroundColor = [UIColor greenColor];
[greenButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[greenButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.scollView addSubview:greenButton];
...
Can you see if this is possible
- (void)addButtonsToScrollView
{
NSArray *buttons = #[#{#"Tag":#2,#"Title":#"red",#"Color":[UIColor redColor]},
#{#"Tag":#3,#"Title":#"blue",#"Color":[UIColor blueColor]},
#{#"Tag":#5,#"Title":#"green",#"Color":[UIColor greenColor]}];
CGRect frame = CGRectMake(0.0f, 0.0f, 50.0f, 30.0f);
for (NSDictionary *dict in buttons)
{
UIButton *button =[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
button.tag = [dict[#"Tag"] integerValue];
[button setTitle:dict[#"Title"]
forState:UIControlStateNormal];
button.backgroundColor = dict[#"Color"];
[button setTitleColor:[UIColor blackColor]
forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
frame.origin.x+=frame.size.width+20.0f;
}
CGSize contentSize = self.scrollView.frame.size;
contentSize.width = frame.origin.x;
self.scrollView.contentSize = contentSize;
}
You can use:
[NSArray arrayWithObjects:redButton,greenButton,blueButton,nil];
But might be better off using a NSDictionary
[NSDictionary dictionaryWithObjectsAndKeys:
redButton, #"red",
blueButton, #"blue",
greenButton, #"green",
nil];
That way you can use the key to look them up instead of index.
Ok, we have the solution, try this code mate,
-(void) createButtons{
NSDictionary *buttonColors = #{#"Red":[UIColor redColor],#"Green":[UIColor greenColor],#"Black":[UIColor blackColor],#"Yellow":[UIColor yellowColor],#"Blue":[UIColor blueColor]};
int tag = 1;
for(NSString *key in buttonColors.allKeys){
UIColor *color = [buttonColors objectForKey:key];
UIButton *button =[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect frame = CGRectMake(((tag -1)*70), 0, 50, 30);
[button setFrame:frame];
button.tag = tag;
button.backgroundColor = color;
[button setTitleColor:color forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:key forState:UIControlStateNormal];
[self.scrollView addSubview:button];
tag++;
}
}

Resources