我有一个有6个按钮的viewcontroller。我有一个服务,我从中获取数组中的字典作为响应:
[
{"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"}
]
我想在运行时使用各自的ID设置按钮标题作为我的按钮的标题但是我无法理解我如何使用此响应将当前标题设置为名称和id为id?
答案 0 :(得分:0)
我在这里快速了解如何执行此操作。
最初创建按钮并在NSMutableArray
中添加所有按钮。将他们的名字设置为""就在请求之前。获得响应后,使用按钮Array执行循环。在每个循环内部,再次执行循环,使用元素的索引检查id
并设置标题。
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];
}
}
}
答案 1 :(得分:0)
使用谓词按升序对id值进行排序,并将按钮Title设置为具有相应的ID值
简单易用
NSArray *buttons=[[NSArray alloc]initWithObjects:self.button1,self.button2,self.button3,self.button4,self.button5,self.button6, nil];
NSArray *array= @[@{@"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"}];
NSSortDescriptor * idDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Id" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:idDescriptor];
NSArray * sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
for (int i=0; i< sortedArray.count; i++) {
[[buttons objectAtIndex:i] setTitle:[[sortedArray objectAtIndex:i] valueForKey:@"Name"] forState:UIControlStateNormal];
}
答案 2 :(得分:0)
[
{"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"}
]
这是您的网络服务响应。现在你有6个按钮。
int i =0;
NSDictionary *dic = // Response of Ids and name;
// Set all button tag from 0 to 5;
//Btn1.tag = 0;
for (UIButton *btn in self.view.subviews)
{
if ([btn isKindOfClass:[UIButton class]])
{
if (btn.tag == i) {
NSString *Ids = [NSString stringWithFormat:@"%d",i];
if ([[dic valueForKey:@"Id"] isEqual:Ids]) {
[btn setTitle:[[dic valueForKey:@"Name"]objectAtIndex:i] forState:UIControlStateNormal];
}
}
}
i++;
}