0

我在 UITableViewCell 中显示一个 NSMutableArray 项目,其作用类似于 gridview。单元格中有自定义 UI 按钮。现在,当用户单击一个按钮时,我希望它突出显示。但是当我这样做时,发生的事情是当我单击按钮的颜色变为红色。但是当我单击下一个按钮时,它的颜色也变为红色,但前一个按钮的颜色也是红色。我希望前一个按钮保持未突出显示,当前按钮突出显示。我该如何做吗?这是我的代码:

 - (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);

}

我该怎么做?

4

1 回答 1

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]];
        }
    }];
}
于 2012-10-11T15:56:23.763 回答