【问题标题】:How to UIButton state in UITableViewCell?如何在 UITableViewCell 中设置 UIButton 状态?
【发布时间】:2013-10-11 17:54:57
【问题描述】:

有没有办法控制UIButton 中的UIButton 状态(启用/禁用按钮)。我的问题是我在单元格中的UIButton 是在storyboard 中使用viewWithTag 制作的。我已经花了很多时间来整理它,但没有运气。人们大多通过以编程方式为带有单元格indexPath 的按钮分配标签来解决问题。

我知道表格会重复使用单元格,但我只是想问一下是否还有另一种解决问题的方法。如果不可能,我可能必须以编程方式创建按钮。

【问题讨论】:

  • “状态”是什么意思?
  • 我想在点击时禁用按钮。但问题是单元格是重复使用的,所以当我向下滚动表格视图时,其他单元格的按钮也将无法单击。
  • 您有自定义单元格?
  • @MirkoCatalano 我在storyboard 上设计单元,但没有专门的单元类。在-tableView:cellForRowAtIndexPath: 中,我使用带有UIButton *btn = (UIButton *)[cell.contentView viewWithTag:100] 的按钮。并在单击按钮时有一个-setEnable: 的方法。
  • 这是错误的,如果您制作自定义单元格,一切都会变得简单,并且可以使用 prepareToReuse 方法解决您的问题

标签: ios objective-c uitableview uibutton


【解决方案1】:

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

【讨论】:

  • 我之前也尝试过您的解决方案,但它不起作用。当我单击按钮时,该行上的按钮被禁用,但是当向下滚动时,单元格被重用,其他行中的一些按钮也被禁用:(。这是因为我的按钮标签未设置为对应于indexPath . 正如我所提到的,我只是使用storyboard 创建了一个按钮,并由-viewWithTag: 使用它
【解决方案2】:

你必须像这样制作一个自定义单元格:

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”,将您的按钮添加到您的自定义单元格并连接 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

【讨论】:

  • Tks 为您提供详细的解决方案,我试过了,但没有用。每当重用单元格时,按钮状态都会重置
【解决方案3】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多