Как отловить событие переключения, измененное в пользовательском tableViewCell? - PullRequest
1 голос
/ 24 марта 2011

У меня есть вопрос ...

У меня есть пользовательский класс TableViewCell:

// Class for Custom Table View Cell.
@interface CustomTableViewCell : UITableViewCell {
    // Title of the cell.
    UILabel*     cellTitle;
    // Switch of the cell.
    UISwitch*    cellSwitch;
}

Как вы можете видеть в моем пользовательском UITableViewCell у меня есть контроллер меток и переключателей.

- (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;
}

Теперь, когда я использую свою пользовательскую ячейку в TableView, я хочу отлавливать событие, когда пользователь меняет состояние switch .Как я могу это сделать?

Ответы [ 3 ]

5 голосов
/ 24 марта 2011

Вы должны написать метод для изменения значения, как показано ниже:

[cellSwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];

Тогда вам нужно реализовать делегат

@protocol SwitchDelegate <NSObject>
- (void)valueChangeNotify:(id)sender;
@end

тогда вы должны сделать делегирование и синтез идентификатора объекта с помощью (nonatomic, assign) правильно и методом, как показано ниже:

- (void)valueChange:(id)sender{
  if ([delegate respondToSelector:@selector(valueChangeNotify:)])
    [delegate valueChangeNotify:sender];
}

Таким образом, вы можете получить уведомление об изменении состояния в контроллере представления.

3 голосов
/ 24 марта 2011

Установите целевое действие для коммутатора, который будет уведомлен об изменениях.

Для этого звоните

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

при создании ячейки.

1 голос
/ 24 марта 2011
@protocol SwitchDelegate
- (void)valueChangeNotify:(id)sender;
@end

// Class for Custom Table View Cell.
@interface CustomTableViewCell : UITableViewCell {
    // Title of the cell.
    UILabel*     cellTitle;
    // Switch of the cell.
    UISwitch*    cellSwitch;

    id<SwitchDelegate> delegate;
}

@property (nonatomic, assign) id <SwitchDelegate> delegate;

@end


- (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 )];
        [cellSwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];


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

        [cellTitle release];
        [cellSwitch release];
    }
    return self;
}




   -(void)valueChange:(id)sender{
        if([delegate respondToSelector:@selector(valueChangeNotify:)])      [delegate valueChangeNotify:sender];     
}

но я получаю беспокойство: "- responseToSelector" не найдено в протоколе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...