iphone - 带有自定义 UIButton 的 UITableViewCell

标签 iphone objective-c ios

我正在尝试创建一个 UITableView带有自定义UIButton在每个表格单元格中。我是这样实现的..

@implementation CouponDetailsCustomTableViewCell

          ...............

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor whiteColor]];

        CGRect frame = self.contentView.frame;

        self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.radioButton setImage:[UIImage imageNamed:@"radio_blank.png"] forState:UIControlStateNormal];
        [self.radioButton setImage:[UIImage imageNamed:@"radio_selected"] forState:UIControlStateSelected];
        [self.radioButton setFrame:CGRectMake(16, 10, 29, 29)];
        [self.radioButton addTarget:nil action:@selector(radioButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:radioButton];
}


@end

和 UITableView 委托(delegate)一样......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *COUPON_CELL_ID = @"CouponCell" ;

    CouponDetailsCustomTableViewCell * couponCell = (CouponDetailsCustomTableViewCell *) [tableView dequeueReusableCellWithIdentifier:COUPON_CELL_ID];
    if (couponCell == nil) {
        couponCell = [[[CouponDetailsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:COUPON_CELL_ID] autorelease];
        couponCell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    [couponCell.radioButton setSelected:NO];
    return couponCell;
}

并且 radioButtonPressed 方法是
-(void)radioButtonPressed:(id) sender
{
     [sender setSelected:YES];
}

现在我运行程序和自定义 UIButton显示在每个表格行中。如果我单击一个按钮,它将被选中(显示 radio_selected.png)。

当我向下滚动表格时出现问题(我在窗口中只显示了 4 行表格)。当我再次向上滚动时..我看到的是单击的按钮显示radio_blank.png .

我是 iPhone 开发的新手。我不知道为什么会这样。我能猜到的最多的是按钮属性正在改变.. setSelected:NO .

有人请给我建议来解决这个问题。

谢谢你。

最佳答案

当您滚动 UITableView 时,隐藏的单元格不再呈现,并且可能会被重用于变得可见的单元格。如果新单元格变得可见,tableView:cellForRowAtIndexPath:被调用。

问题是您正在设置 已选择在那里声明:

[couponCell.radioButton setSelected:NO];

因此,每当您将单元格滚动出可见区域并再次返回时,它都会重置为 selected = NO .

我建议你创建一个 NSMutableDictionary存储每行/NSIndexPath 的选择状态的位置,然后在 tableView:cellForRowAtIndexPath: 中重新应用.

关于iphone - 带有自定义 UIButton 的 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10615320/

相关文章:

iphone - 如何在 Core Data 中选择特定的数据?

ios - TableView(搜索结果 TableView )有时会意外滚动

ios - 我怎样才能使用 AVAudioPlayer 更快*和*更高音调地播放音频?

ios - cocoapods pod lib 创建和方案

android - 测试移动端的 HTML/CSS 模板

ios - 将以前的用户代理设置为 webview

iphone - iPhone SIGABRT崩溃0x00000000:帮助我进行多项选择

objective-c - 类别和实例变量

c++ - 无法为arm64和x86_64架构构建opencv ios框架

iPhone:当用户触摸背景时关闭键盘