我如下解決了這個問題。
- (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
這是我的實現。如果你能發表評論,我會很高興。因爲我不知道這是我的問題的正確解決方案。謝謝!