Кнопка флажка в представлении таблицы в iPhone - PullRequest
0 голосов
/ 27 декабря 2010

Я хочу создать флажок в каждой строке в табличном представлении.Мой код работает только для одного флажка.Если у меня есть больше чем 1, это терпит неудачу.Мой код

  UIButton   * checkBox=[UIButton buttonWithType:UIButtonTypeCustom];
        checkBox.tag=indexPath.row;
        checkBox.frame=CGRectMake(270,15, 20, 20);
        [cell.contentView addSubview:checkBox];
        [checkBox setImage:[UIImage imageNamed:@"selectedBoxWith.png"] forState:UIControlStateNormal];
        [checkBox addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];

-(void)checkBoxClicked:(id)sender{
if(self.isChecked ==NO){
  self.isChecked =YES;
  [sender  setImage:[UIImage imageNamed: @"selectedBoxWithTik.png"] forState:UIControlStateNormal];
}else
{
   self.isChecked =NO;
  [sender setImage:[UIImage imageNamed:@"selectedBoxWith.png"]forState:UIControlStateNormal];

    }
}

Как я могу справиться с этим, чтобы узнать больше?

Ответы [ 3 ]

3 голосов
/ 27 декабря 2010

Вам просто нужно попробовать это.Это будет работать ..........

-(void)checkBoxClicked:(id)sender{

    UIButton *tappedButton = (UIButton*)sender;

    if([tappedButton.currentImage isEqual:[UIImage imageNamed:@"selectedBoxWith.png"]]) {
        [sender  setImage:[UIImage imageNamed: @"selectedBoxWithTik.png"] forState:UIControlStateNormal];
    }

    else {
        [sender setImage:[UIImage imageNamed:@"selectedBoxWith.png"]forState:UIControlStateNormal];
    }
}
1 голос
/ 27 декабря 2010

Вы не можете просто сделать это с помощью простого UIButton, так как вам нужно будет определить, какой флажок номера строки был нажат. Следовательно, вместо использования UIButton непосредственно используйте CustomButton, который расширяет UIButton и имеет дополнительное свойство rowTag, например:

@interface CustomButton : UIButton {
  NSInteger rowTag;
}

@property NSInteger rowTag;

@end

@implementation CustomButton

@synthesize rowTag;

@end

Сейчас в cellForRowAtIndexPath:

if(cell==nil){
        CustomButton   * checkBox=[CustomButton buttonWithType:UIButtonTypeCustom];
        checkBox.tag=21;
        checkBox.frame=CGRectMake(270,15, 20, 20);
        [cell.contentView addSubview:checkBox];
        [checkBox addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
}
    CustomButton *btn = [cell.contentView viewWithTag:21];
    [btn setRowTag:indexPath.row];
    if(selectedProperty){
       [checkBox setImage:[UIImage imageNamed:@"selectedBoxWithTik.png"] forState:UIControlStateNormal];
    }
    else
       [checkBox setImage:[UIImage imageNamed:@"selectedBoxWith.png"] forState:UIControlStateNormal];

Надеюсь, это поможет.

0 голосов
/ 03 октября 2014

Например, нажатие на первую строку используется для изменения других строк.Нажмите на другие строки только изменить себя.arrCheckbox - это массив, используемый для хранения проверки всех строк.

- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"AV--%s", __func__);
    HistoryCell2 *cell = [tableview dequeueReusableCellWithIdentifier:CellId];

    if (cell == nil) {
        NSLog(@"Create new row");
        [tableview registerNib:[UINib nibWithNibName:@"HistoryCell2" bundle:nil] forCellReuseIdentifier:CellId];
        cell = [tableview dequeueReusableCellWithIdentifier:CellId];
    }
    cell.tag = indexPath.row;

    BOOL checked =  [[arrCheckbox objectAtIndex:indexPath.row] boolValue];
    UIImage *image = (checked) ? [UIImage imageNamed:@"cb_on.png"] : [UIImage imageNamed:@"cb_off.png"];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(1.0, 1.0, 29, 29);
    button.frame = frame;   // match the button's size with the image size
    button.tag = indexPath.row;
    [button setBackgroundImage:image forState:UIControlStateNormal];

    // set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
    [button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button];

    return cell;
}

- (void) checkButtonTapped:(id)sender
{
    NSLog(@"%s", __func__);
    UIButton *tappedButton = (UIButton*)sender;
    int index = (int)tappedButton.tag;
    NSLog(@"Row button: %d", index);

    if(index > 0)
    {
        BOOL checked = [[arrCheckbox objectAtIndex:index] boolValue];
        [arrCheckbox removeObjectAtIndex:index];
        [arrCheckbox insertObject:(checked) ? @"0":@"1" atIndex:index];

        UIImage *newImage = (checked) ? [UIImage imageNamed:@"cb_off.png"] : [UIImage imageNamed:@"cb_on.png"];
        [tappedButton setBackgroundImage:newImage forState:UIControlStateNormal];
    }
    else{
        //UITableView *tableview = (UITableView *)[[tappedButton superview] superview];
        UIImage *newImage;
        BOOL checked = [[arrCheckbox objectAtIndex:0] boolValue];
        for(int i=0; i<[arrCheckbox count]; i++)
        {
            //NSLog(@"Row: %d------", i);
            [arrCheckbox removeObjectAtIndex:i];
            [arrCheckbox insertObject:(checked) ? @"0":@"1" atIndex:i];

            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            for(UIView *subview in cell.contentView.subviews)
            {
                if([subview isKindOfClass: [UIButton class]])
                {
                    //NSLog(@"Modify button");
                    tappedButton = (UIButton*)subview;
                    //[subview removeFromSuperview];
                    newImage = (checked) ? [UIImage imageNamed:@"cb_off.png"] : [UIImage imageNamed:@"cb_on.png"];
                    [tappedButton setBackgroundImage:newImage forState:UIControlStateNormal];
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...