我在UITableViewCell中显示一个NSMutableArray项,就像gridview一样。单元格中有自定义UI按钮。当用户点击一个按钮时我希望它突出显示。但是当我这样做时发生的事情就是当我点击一个按钮,它的颜色变为红色。但是当我点击下一个按钮时,它的颜色也变为红色,但是prevoius按钮的颜色也是红色。我希望prevoius按钮保持不变,并且当前按钮被突出显示。我该怎么做? 这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CGRect rect = CGRectMake(18+80*j, yy,57, 40);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
[button setContentMode:UIViewContentModeCenter];
NSString *settitle=[NSString stringWithFormat:@"%@",item.title];
[button setTitle:settitle forState:UIControlStateNormal];
NSString *tagValue = [NSString stringWithFormat:@"%d%d", indexPath.section+1, i];
button.tag = [tagValue intValue];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[hlcell.contentView addSubview:button];
[button release];
}
-(IBAction)buttonPressed:(id)sender {
int tagId = [sender tag];
int divNum = 0;
if(tagId<100)
divNum=10;
else
divNum=100;
int section = [sender tag]/divNum;
section -=1;
int itemId = [sender tag]%divNum;
UIButton *button = (UIButton *)sender;
if(button.enabled==true)
{
button.backgroundColor=[UIColor redColor];
}
NSLog(@"…section = %d, item = %d", section, itemId);
NSMutableArray *sectionItems = [sections objectAtIndex:section];
Item *item = [sectionItems objectAtIndex:itemId];
NSLog(@"..item pressed…..%@, %@", item.title, item.link);
}
我该怎么做?
答案 0 :(得分:0)
这样做的一种方法是为头文件中的所有按钮保留一个IBCollection引用(将Interface builder中的所有按钮连接到此IBOutletCollection):
@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *allOfMyButtons;
并且在你的buttonPressed方法中,只有当当前按下的按钮和该按钮被启用时才会使背景颜色变为红色(所有其他按钮变回黑色或任何初始颜色):
-(IBAction)buttonPressed:(id)sender {
[self.allOfMyButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIButton *button = (UIButton *)obj;
if (button != sender && button.enabled) {
[button setBackgroundColor:[UIColor redColor]];
} else {
[button setBackgroundColor:[UIColor blackColor]];
}
}];
}