2011-12-12 57 views
0

我遇到問題。 我希望我的表格顯示我的自定義單元格。每個小區包含一個按鈕(參見所附文件)根據自定義單元格創建UITableView

enter image description here

在該方法的cellForRowAtIndexPath我返回自定義單元格。自定義單元格包含一個UIButton,如附圖所示。

我的問題是如下 - 當我按下按鈕應該點亮(紅色)和其他按鈕應該是衰減(藍色)。如何在對象之間建立連接?

我會很高興與任何答案!謝謝!

這是我實現的UITableViewController類:

回答

0

我如下解決了這個問題。

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

這是我的實現。如果你能發表評論,我會很高興。因爲我不知道這是我的問題的正確解決方案。謝謝!

相關問題