自定义TableViewCell - 与TableViewController通信

时间:2013-07-06 13:12:28

标签: ios uitableview

我有一个Custom TableViewCell,它有一个复选框,状态应该保持持久性。我的问题是如何让tableView与Custom Cell通信,例如当我在用户按下按钮时存储对象时我需要知道用户按下按钮的哪一个TableView行,我需要能够传递它TableView中的键用于NSUserDefaults键。我该怎么做?

- (IBAction)flagLectureButtonPressed:(UIButton *)sender
{
    NSLog(@"sender %@",sender.description);
        UIImage* selectedButton=[UIImage imageNamed:@"checkmarkSelected.png"];
        UIImage* unselectedButton=[UIImage imageNamed:@"checkmark.png"];

        if (sender.currentImage == unselectedButton) {
            [sender setSelected:YES];
            [sender setImage:selectedButton forState:UIControlStateNormal];
            [self saveflagButtonState:kButtonFlagged forButton:sender];
        } else {
            [sender setSelected:NO];
            [sender setImage:unselectedButton forState:UIControlStateNormal];
            [self saveflagButtonState:kButtonNormal forButton:sender];
        }
}

- (void) saveflagButtonState:(ButtonState)state forButton: (UIButton *)sender
{
    static int i = 0;
    NSString *object;
    if (state == kButtonFlagged) {
        object = @"flaged";
    } else if (state == kButtonNormal) {
        object = @"normal";
    }

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:object forKey:@"key"];
    [defaults synchronize];
}

- (void) setTagLectureButton:(UIButton *)tagLectureButton
{

    UIImage* selectedButton=[UIImage imageNamed:@"checkmarkSelected.png"];
    UIImage* unselectedButton=[UIImage imageNamed:@"checkmark.png"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *buttonIsTaged = [defaults stringForKey:@"key"];
    if (buttonIsTaged) {
        [tagLectureButton setImage:selectedButton forState:UIControlStateNormal];
    } else {
        [tagLectureButton setImage:unselectedButton forState:UIControlStateNormal];
    }
}

@end

1 个答案:

答案 0 :(得分:2)

一种好方法是使用自定义单元类。让该单元类管理按钮以及它对用户交互的反应。单元格应提供保存标识信息的属性(您在tableView:cellForRowAtIndexPath:中配置)。单元格还应提供一个回调,该回调通过单元格本身(这样您就可以获取标识信息并更改单元格的任何属性)和选择状态。类似于customCell:didUpdateSelectionState:

在按钮上设置tag(再次在tableView:cellForRowAtIndexPath:中)然后当你得到按钮事件(flagLectureButtonPressed时,现在在控制器中处理的方法不是很好而不是单元格)你可以得到标签号。


对于回调,您有两个级别的复杂性:1。选择器。 2.协议。选择器选项很简单,但很少提供编译器验证或参数选项。协议方法稍微复杂一点,但验证更好,更灵活。

1

在您的单元子类中,添加了2个属性:

@property (weak, nonatomic) id selectionTarget;
@property (assign, nonatomic) SEL selectionAction;

您依靠自己(或将来维护代码的任何人)来提供正确的格式选择器。然后,当点击按钮时:

[self.selectionTarget performSelector:self.selectionAction withObject:self withObject:selectionState];

请注意,selectionState在这种情况下是NSNumber / NSString / etc(对象,不是整数)。

2

您定义一个协议(用合理的名称替换......):

@protocol ...CellDelegate
- (void)customCell:(... *)cell didUpdateSelectionState:(ButtonState)state;
@end

然后向单元格添加1个属性:

@property (weak, nonatomic) id < ...CellDelegate > selectionDelegate;

然后,点击按钮时:

[self.selectionDelegate customCell:self didUpdateSelectionState:selectionState];