Я решил эту проблему следующим образом:
Это моя реализация класса UITableViewController.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.delegate = self;
[cells addObject:cell];
// Configure the cell...
return cell;
}
- (void)mustDeselectWithout:(CustomCell *)cell{
for (CustomCell * currentCell in cells) {
if(currentCell != cell){
[currentCell deselect];
}
}
}
Как вы видите, когда я создаю ячейки, я возвращаю пользовательскую ячейку в методе cellForRowAtIndexPath.
Это класс пользовательской ячейки
.h
#import <UIKit/UIKit.h>
#import "ProtocolCell.h"
@interface CustomCell : UITableViewCell {
UIButton * button;
}
@property(nonatomic, assign) id<ProtocolCell> delegate;
- (void)select;
- (void)deselect;
@end
и .m
#import "CustomCell.h"
@implementation CustomCell
@synthesize delegate;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(5, 5, 25, 25)];
[button setBackgroundColor:[UIColor blueColor]];
[button addTarget:self action:@selector(select) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:button];
}
return self;
}
- (void)select{
[button setBackgroundColor:[UIColor redColor]];
[delegate mustDeselectWithout:self];
}
- (void)deselect{
[button setBackgroundColor:[UIColor blueColor]];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc
{
[super dealloc];
}
@end
Мой класс UITableViewController реализует протокол ProtocolCell . Когда я нажимаю на кнопку, мой делегат вызывает метод mustDeselectWithout и отменяет выбор всех кнопок в моем массиве без текущей кнопки.
#import <Foundation/Foundation.h>
@class CustomCell;
@protocol ProtocolCell <NSObject>
- (void)mustDeselectWithout:(CustomCell *)cell;
@end
Это моя реализация. Если бы вы могли комментировать, я буду счастлив. Потому что я не знаю, является ли это правильным решением моей проблемы или нет. Спасибо!