2013-10-11 37 views
2

無論如何要控制UIButton狀態(啓用/禁用按鈕)在UITableViewCell。我的問題是我的UIButton在單元格中使用viewWithTagstoryboard中生成。我花了相當多的時間來整理,但沒有運氣。人們主要通過編程爲單元格indexPath分配按鈕標籤來解決問題。如何在UITableViewCell中的UIButton狀態?

我知道表格將重用單元格,但我只是想問問是否有另一種哈希方式來解決我的問題。如果不可能,我可能不得不以編程方式創建按鈕。

+0

你是什麼意思與「國家」? –

+0

我想單擊時禁用按鈕。但問題是單元格被重用,所以當我向下滾動表格視圖時,其他單元格的按鈕將無法點擊。 – babygau

+0

你有一個自定義的單元格? –

回答

0

你可以遍歷單元格的所有子視圖,並檢查它們是否是使用isMemberOfClass獲取按鈕的UIButton。如果你有多個按鈕,你可以檢查按鈕的文本或其他一些唯一標識它的屬性。這將是一個黑客的方式來做到這一點。

+0

我也嘗試過你的解決方案,但它不起作用。當我點擊按鈕時,該行上的按鈕被禁用,但向下滾動時,單元格被重用,其他行中的某些按鈕也被禁用:(這是因爲我的按鈕標記未設置爲對'indexPath'的響應。正如我所提到的,我只是使用'storyboard'創建了一個按鈕,並通過'-viewWithTag:' – babygau

0

你必須作出這樣一個自定義單元格:

CustomCell.h

@protocol CustomCellDelegate <NSObject> 

- (void)buttonPressed:(UIButton *)sender; 


@end 
#import <UIKit/UIKit.h> 

@interface CustomCell : UITableViewCell 

@property (weak, nonatomic) id<CustomCellDelegate> delegate; 
@property (weak, nonatomic) IBOutlet UIButton *button; 

- (IBAction)buttonPressed:(UIButton *)sender; 
@end 

CustomCell.m

#import "CustomCell.h" 

@implementation CustomCell 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

-(void)prepareForReuse{ 
    self.button.enable = YES; 
} 


- (IBAction)buttonPressed:(UIButton *)sender{ 
[self.delegate buttonPressed:sender]; 
} 
@end 

後IB添加一個新的UITableViewCell在你的UITableView和它的類中,新的自定義單元格將標識ID設置爲「Cust」 omCell」您的按鈕添加到您的自定義單元格並連接插座,然後修改您的tableView:的cellForRowAtIndexPath:像:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
static NSString *[email protected]"CustomCell"; 
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

cell.delegate = self; 

return cell; 
} 

- (void)buttonPressed:(UIButton *)sender{ 
sender.enable = NO; 
} 

你也必須添加CustomCellDelegate在控制器的加熱器文件

+0

Tks mate爲您的細節解決方案使用它,我嘗試過但不工作。每當單元格被重用時,按鈕狀態被重置 – babygau

+0

刪除prepareFOrReuse方法,代碼工作 –

+0

它仍然不起作用。問題一直存在 – babygau

0

一個簡單方法是在您的視圖控制器中保留一個NSMutableArray變量,並跟蹤哪些單元格按鈕被禁用/啓用。並使用UITableViewDataDelegate方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

每次顯示時都會設置按鈕狀態。和UITableViewDelegate方法:

– tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)tableViewCell forRowAtIndexPath:(NSIndexPath *)indexPath 

寫入數組。使用indexPath進行索引。