问题:如何定位众多动态创建的 UIButton 之一,以便更改其属性?
背景:我有一个带有 UIViewConroller 的故事板。当这个 UIVC 加载一个 UIScrollView 时,会添加一个 UIImageView ,该 UIImageView 有一个展览平面图。每个参展商在包含其在平面图上的位置的数据库中都有一个条目。加载 UIVC 时,将为所有参展商运行一个循环,并且每个参展商都有一个 UIButton 绘制在 UIIV 上。单击 UIB 时,按钮背景颜色会更改(以确认已选择哪个参展商),并显示 UIAlertView 以及有关该参展商的信息。当按下 UIAV 的“取消”(确定)按钮时,UIAV 会关闭,并且应该删除之前应用的背景突出显示颜色,但这是我遇到问题的地方。我无法定位 UIButton,因此我可以更改其背景颜色。
到目前为止我已经尝试过:在创建每个按钮时,我给它一个标签和一个标题,并将它们记录在一个数组中。当在 UIAlertView 上按下“取消”按钮时,我尝试检查数组中的标记,但我仍然无法真正定位 UIButton。
我在想这样的事情:
// obviously not correct syntax but the kind of thing I want
[exhibitorBtn(tag) setBackgroundColor:[UIColor greenColor]];
所以,假设我有 12 个 UIButton,它们都称为 existorBtn,但标题和标签不同:
对象 ----- 名称 ---------- 标题 -------- 标记
UIButton -- 参展商Btn -- 葛兰素 ------ 1
UIButton -- 参展商Btn -- Porsche --- 2
UIButton --existorBtn --Rolex ------- 3 < 我将如何定位该按钮的属性?
编辑 - 添加创建按钮的代码只是为了澄清:
for (NSDictionary *dict in exhibitorStandArray) {
NSInteger currentPosition = [exhibitorStandArray indexOfObject:dict];
NSLog(@"Position in array = %li", (long)currentPosition);
if (![dict[@"locCoords"] isEqual: @""]) {
NSInteger buttonTag = [exhibitorStandArray indexOfObject:dict];
NSString *standNo = dict[@"locStandNo"];
NSMutableDictionary *buttonDictionary = [[NSMutableDictionary alloc] init];
[buttonDictionary setObject:[NSNumber numberWithInteger:buttonTag] forKey:@"buttonTag"];
[buttonDictionary setObject:standNo forKey:@"buttonStandNo"];
[_masterButtonList addObject:buttonDictionary];
NSString *locCoords = dict[@"locCoords"];
NSArray *tempArray =[locCoords componentsSeparatedByString:@","];
tlcTop = [[tempArray objectAtIndex:0] integerValue];
tlcLeft = [[tempArray objectAtIndex:1] integerValue];
brcTop = [[tempArray objectAtIndex:2] integerValue];
brcRight = [[tempArray objectAtIndex:3] integerValue];
buttonWidth = brcRight - tlcLeft;
buttonHeight = brcTop - tlcTop;
testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
testBtn.frame = CGRectMake(tlcTop, tlcLeft, buttonHeight, buttonWidth);
testBtn.titleLabel.text = standNo;
testBtn.tag = buttonTag;
NSLog(@"UIButton Title = %@", testBtn.titleLabel.text);
NSLog(@"UIButton Tag = %li", (long)testBtn.tag);
testBtn.titleLabel.hidden = YES;
[testBtn addTarget:self action:@selector(displayInfo:) forControlEvents:UIControlEventTouchUpInside];
[_buttonArray addObject:testBtn];
[_imageView addSubview:testBtn];
}
}