如何在自定义tableViewCell中捕获切换事件?

Vik*_*yan 1 iphone events uitableview ios

我有个问题 ...

我有Custom TableViewCell类:

// Class for Custom Table View Cell.
@interface CustomTableViewCell : UITableViewCell {
    // Title of the cell.
    UILabel*     cellTitle;
    // Switch of the cell.
    UISwitch*    cellSwitch;
}
Run Code Online (Sandbox Code Playgroud)

如何在我的自定义UITableViewCell中看到我有Label和Switch控制器.

- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum {
        // Get Self.
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            // Create and initialize Title of Custom Cell.
            cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, (44 - TAGS_TITLE_SIZE)/2, 260, 21)];
            cellTitle.backgroundColor      = [UIColor clearColor];
            cellTitle.opaque               = NO;
            cellTitle.textColor            = [UIColor blackColor];
            cellTitle.highlightedTextColor = [UIColor whiteColor];
            cellTitle.font                 = [UIFont boldSystemFontOfSize:TAGS_TITLE_SIZE];
            cellTitle.textAlignment        = UITextAlignmentLeft;
            // Create and Initialize Switch of Custom Cell.
            cellSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(185, 10, 10, 10 )];

            [self.contentView addSubview:cellTitle];
            [self.contentView addSubview:cellSwitch];

            [cellTitle release];
            [cellSwitch release];
        }
        return self;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我在TableView中使用自定义单元格时,我希望在用户更改开关状态时捕获事件.我怎样才能做到这一点 ?

小智 5

您必须编写值更改方法,如下所示:

[cellSwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
Run Code Online (Sandbox Code Playgroud)

然后你必须实现委托

@protocol SwitchDelegate <NSObject>
- (void)valueChangeNotify:(id)sender;
@end
Run Code Online (Sandbox Code Playgroud)

那么你必须使用(非原子,赋值)属性和方法使对象id委托和合成如下:

- (void)valueChange:(id)sender{
  if ([delegate respondToSelector:@selector(valueChangeNotify:)])
    [delegate valueChangeNotify:sender];
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以在视图控制器中获取通知状态更改.