2014-01-16 23 views
1

我使用這個配件在細胞中的TableView:UITableViewCell的定製附件按鈕

cell.accessoryType = UITableViewCellAccessoryDetailButton; 

我想這個細節按鈕,看起來像在文本字段清除按鈕雖然。我該怎麼做,仍然能夠使用accessoryButtonTappedForRowWithIndexPath:indexPath方法。

+0

我在這裏找到了答案: http://stackoverflow.com/questions/869421/using-a-custom-image-for-a- uitableviewcells-accessoryview-and-having-it-respond – ZviBar

回答

3

唯一的方法是繼承你的UITableViewCell。讓它成爲CustomTableViewCell。然後寫協議CustomTableViewCell,其中定義方法

@protocol CustomTableViewCellDelegate 

- (void)customButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath; 

@end 

然後定義委託,並在您的YourTableViewController落實協議

#import "CustomTableViewCell.h" 

@interface YourTableViewController : UITableViewController <CustomTableViewCellDelegate> 

@property (nonatomic, weak) id<CustomTableViewCellDelegate> delegate; 

.............................. 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChatTableViewCellIdentifier forIndexPath:indexPath]; 

    cell.delegate = self; 
    cell.indexPath = indexPath; 
    .......... 
} 

- (void)customButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath 
{ 
    <YOUR_CODE_FOR_PRESS_HANDLER> 
} 

CustomTableViewCell描述:

@protocol CustomTableViewCellDelegate; 

@interface CustomTableViewCell : UITableViewCell 

@property (nonatomic, strong) NSIndexPath *indexPath; 

@end 

................... 


@implementation CustomTableViewCell 

- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { 

    UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    yourButton.frame = CGRectMake(0, 0, 25, 25); 

    [yourButton.frame setBackgroundImage:[UIImage imageNamed:@"clear_image_name"] forState:UIControlStateNormal]; 
    [yourButton.frame setBackgroundImage:[UIImage imageNamed:@"clear_image_name_pressed"] forState:UIControlStateHighlighted]; 

    self.accessoryView = yourButton; 
    [yourButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    return self; 
} 

- (void) buttonPressed:(id)sender 
{ 
    [self.delegate customButtonTappedForRowWithIndexPath:self.indexPath]; 
} 
+0

在這段代碼中,我看不到按鈕外觀在UITextField中的清除按鈕的位置。 – ZviBar