Как добавить кнопку флажки в UITableViewCell цель c - PullRequest
0 голосов
/ 23 октября 2018

Я знаю здесь очень много ответов на этот вопрос, но я не могу получить правильное значение для всех.

Я хочу, чтобы кнопка выбора не была ячейкой.по умолчанию кнопка не отмечена, и если какой-то один щелчок или нажатие на кнопку, то кнопка заменяется на проверенную (только нажимает кнопку), а не на все.

Я упомянул свой скриншот, и в коде есть кнопка, значения массива (имя устройства)и что-то с кнопкой переключателя

код

-(IBAction)SelectAppliance:(id)sender {
    UIButton *btn=(UIButton*)sender;
    NSLog(@"button tag is :%ld",(long)btn.tag);
    NSLog(@"click button"); 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_arrApplnc count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"SceneTableViewCell";

    SceneTableViewCell *cell = (SceneTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if(checked) { 
         [cell.btnRadio setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    } else {
         [cell.btnRadio setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
    }

    cell.btnRadio.tag = indexPath.row;
    cell.lblName.text =[[_arrApplnc valueForKey:@"applianceName"] objectAtIndex:indexPath.row];
    [cell.btnRadio addTarget:self action:@selector(SelectAppliance:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

UI Screenshort

1 Ответ

0 голосов
/ 23 октября 2018

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

В SceneTableViewCell.h

@protocol SceneTableViewCellDelegate <NSObject>
@optional
    - (void)checkBoxTapped:(SceneTableViewCell *)cell;
@end

@interface SceneTableViewCell : NSObject
    @property (nonatomic, weak) id <SceneTableViewCellDelegate> delegate;
@end

В SceneTableViewCell.m

-(IBAction)checkboxTapped:(UIButton *)sender {
    [self.delegate checkBoxTapped:self];
}

В вашем ViewController.m

@property (nonatomic,strong) NSMutableIndexSet *checkedRows;

- (void) viewDidLoad {
    self.checkedRows = [[NSMutableIndexSet alloc]init];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"SceneTableViewCell";

    SceneTableViewCell *cell = (SceneTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self
    }


    if([self.checkedRows contains:indexPath.row]) { 
         [cell.btnRadio setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    } else {
         [cell.btnRadio setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
    }

    cell.lblName.text =[[_arrApplnc valueForKey:@"applianceName"] objectAtIndex:indexPath.row];

    return cell;
}

- (void) checkBoxTapped:(SceneTableView Cell *)cell {

    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    if ([self.checkedRows contains: indexPath.row]) {
        [self.checkedRows removeIndex: indexPath.row];
    } else {
        [self.checkedRows addIndex: indexPath.row];
    }

    [tableView reloadRowsAt:@[indexPath], withRowAnimation: UITableViewRowAnimationAutomatic];
}

Другим подходом было бы просто использовать UIImageView в ячейке, а не UIButton и использовать обработчик didSelect для переключения проверенного состояния.Таким образом, пользователь может нажать в любом месте ячейки.

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