如何在UITableViewCell中使用UIButton状态?

时间:2013-10-11 17:54:57

标签: ios objective-c uitableview uibutton

无论如何都要在UIButton中控制UITableViewCell状态(启用/禁用按钮)。我的问题是我的UIButton单元格是storyboard使用viewWithTag制作的。我花了很多时间来解决它,但没有运气。人们主要通过以编程方式为单元格indexPath分配按钮的标记来解决问题。

我知道该表将重用该单元格,但我只想询问是否有另一种黑客方式来解决我的问题。如果不可能,我可能必须以编程方式创建按钮。

3 个答案:

答案 0 :(得分:0)

您可以遍历单元格的所有子视图,并使用isMemberOfClass检查它们是否为UIButton以获取按钮。如果您有多个按钮,则可以检查按钮的文本或其他唯一标识它的属性。这将是一种hacky方式。

答案 1 :(得分: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之后,你在你的UITableView上添加一个新的UITableViewCell,并在你的新自定义单元格的类中设置识别ID,如“CustomCell”,将你的Button添加到自定义单元格并连接Outlet,然后修改你的tableView: 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;
}

此外,您还必须在控制器的加热器文件中添加CustomCellDelegate

答案 2 :(得分:0)

一种简单的方法是在视图控制器中保留一个NSMutableArray变量,并跟踪它是否禁用/启用了哪些单元格按钮。并使用UITableViewDataDelegate方法:

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

每次显示时设置按钮状态。和UITableViewDelegate方法:

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

写入数组。使用indexPath进行索引。