无论如何都可以控制UITableViewCell
中的UIButton
状态(启用/禁用按钮)。我的问题是我在单元格中的UIButton
是使用 viewWithTag
在 storyboard
中进行的。我一直花了很多时间来解决这个问题,但没有运气。人们大多通过以编程方式为带有单元格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,并且它的类与您一起设置了识别ID,例如"自定义单元格",将您的按钮添加到自定义单元格并连接插座,然后修改表视图:cellForRowAtIndexPath:像这样:
-(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;
}
此外,您还必须在控制器的加热器文件中添加自定义单元代表
一种简单的方法是在视图控制器中保留一个 NSMutableArray 变量,并跟踪禁用/启用的单元格按钮。并使用 UITableViewDataDelegate 方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
以设置每次显示按钮时的状态。和 UITableViewDelegate 方法:
– tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)tableViewCell forRowAtIndexPath:(NSIndexPath *)indexPath
写入数组。使用 indexPath 进行索引。