[英]How to UIButton state in UITableViewCell?
無論如何在UITableViewCell
控制UIButton
狀態( 啟用/禁用按鈕 )。 我的問題是我的單元格中的UIButton
是使用viewWithTag
在storyboard
viewWithTag
。 我已經花了很多時間來解決它,但是沒有運氣。 人們通常通過以編程方式為單元格indexPath
分配按鈕的標簽來解決問題。
我知道該表將重用該單元格,但我只是想問一下是否還有另一種破解我的問題的方法。 如果不可能,則可能需要以編程方式創建按鈕。
您可以遍歷單元格的所有子視圖,並使用isMemberOfClass
來檢查它們是否為UIButton來獲取按鈕。 如果您有多個按鈕,則可以檢查按鈕的文本或唯一標識它的其他屬性。 那將是一種駭人聽聞的方式。
您必須制作一個這樣的自定義單元:
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中,您在UITableView處添加了一個新的UITableViewCell,並使用新的自定義單元格將其類設置為Identify ID,例如“ CustomCell”,將您的Button添加到您的自定義單元格並連接了Outlet,然后修改了tableView:cellForRowAtIndexPath:like那:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=@"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.delegate = self;
return cell;
}
- (void)buttonPressed:(UIButton *)sender{
sender.enable = NO;
}
另外,您還必須在控制器的加熱器文件中添加CustomCellDelegate
一種簡單的方法是將NSMutableArray變量保留在視圖控制器中,並跟蹤禁用/啟用了哪些單元格按鈕。 並使用UITableViewDataDelegate方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
在每次顯示時設置按鈕狀態。 和UITableViewDelegate方法:
– tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)tableViewCell forRowAtIndexPath:(NSIndexPath *)indexPath
寫入數組。 使用indexPath建立索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.