0

gridviewのように動作するUITableViewCellにNSMutableArrayアイテムを表示しています。セルにカスタムUIbuttonsがあります。ユーザーが1つのボタンをクリックすると、強調表示されます。ボタンの色が赤に変わります。しかし、次のボタンをクリックすると、その色も赤に変わりますが、前のボタンの色も赤になります.前のボタンを強調表示しないで、現在のボタンを強調表示したい.やれ?これは私のコードです:

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

これを行う 1 つの方法は、すべてのボタンの IBCollection 参照をヘッダー ファイルに保持することです (Interface ビルダーのすべてのボタンをこの 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 に答える