Lovely Lovely - 20 days ago 9
Objective-C Question

Setting current title and id of button from response obtained from service

I have a viewcontroller having 6 buttons.And I have a service from which I am getting dictionary in array as response:

[
{"Id":"2","Name":"Alex"},
{"Id":"5","Name":"AMark"},
{"Id":"1","Name":"Karta"},
{"Id":"7","Name":"Juan"},
{"Id":"6","Name":"Honky"},
{"Id":"3","Name":"Nirauk"},
{"Id":"4","Name":"Chinua"}
]


I want to set the button title as the title of my buttons on run time with respective ids but i am not able to understand that how can I use this response to set the current title as name and id as id?

Answer

Here I'm giving a quick idea of how to do this.

Create the button initially and add all in an NSMutableArray. Set their names as "" just before the request. Once you get the response, Do a loop with button Array. Inside each loop, again do a loop, which checks the id with the index of the element and set the title.

int numberOfButtons = 6;
CGFloat xPos = 10;
CGFloat yPos = 20;
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];

for (int i = 1; i <= numberOfButtons; i++){
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(xPos, yPos, 100, 40)];
    //Button Styles
    yPos += button.frame.size.height;
    button.tag = i;
    [self.view addSubview:button];

    //Add the button into array
    [mutableArray addObject:button];
}


//Get the response. Once you get the response do this.

NSArray *responseArray = [[NSArray alloc] init]; //This should be the response from the server

for (UIButton *button  in mutableArray) {
    for (NSDictionary *dict in responseArray){
        if ([[dict objectForKey:@"Id"] intValue] == button.tag){
            [button setTitle:[dict objectForKey:@"Name"] forState:UIControlStateNormal];
        }
    }
}
Comments