2012-06-25 4 views
2

Я использую пользовательские кнопки флажка в моем представлении таблицы и хочу сохранить данные выбранной ячейки на изменяемый массив .... кто может мне помочь ... СпасибоКак сохранить данные Tableview ячейки

+0

у вас уже есть данные, вам просто нужно, чтобы получить конкретные данные и хранить его другой mutablearray, я прав? – janusbalatbat

+0

отправил мой ответ ... :) – janusbalatbat

ответ

3

создать изменяемый массив для хранения выбранных данных, позволяет называть его «yourSeparatedData», установите метку вашего флажок в cellForRowAtIndexPath и установить onCheck: метод в качестве мишени. код будет выглядеть следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *CellIdentifier = @"setMe"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle……… 
    } 
    checkBox = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    checkBox.frame = CGRectMake(customizeMe); 
    if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:indexPath.row]] != NSNotFound) 
    { 
     [checkBox setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal]; 
    } 
     else { 
     [checkBox setBackgroundImage:[UIImage imageNamed:@"unCheck.png"] forState:UIControlStateNormal]; 
     } 
     [checkBox addTarget:self action:@selector(onCheck:) forControlEvents:UIControlEventTouchUpInside]; 
     [checkBox setTag:indexPath.row]; 

     [cell addSubview:checkBox]; 
     return cell; 

}

-(void)onCheck:(id)sender { 
    if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:[sender tag]]] != NSNotFound) 
     { 
     [sender setBackgroundImage:[UIImage imageNamed:@"unCheck.png"] forState:UIControlStateNormal]; 
     [yourSeparatedData removeObject:[yourTableViewDataSource objectAtIndex:[sender tag]]]; 
     } 
     else { 
     [sender setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal]; 
     [yourSeparatedData addObject:[yourTableViewDataSource objectAtIndex:[sender tag]]]; 
     } 
     [yourTableView reloadData]; 
} 

этот код не проверяется, вы используете опцию таким образом я предполагал, что вы хотите отделить не только один данные, в конце выбор, у вас будет «yourSeparatedData» с объектами, выбранными из вашего tableView.

+0

приветствия .... ваш код мне очень помог. –

+0

добро пожаловать :) – janusbalatbat

0

У вас есть для этого вручную, в UITableView или UITableViewController нет возможности сделать это автоматически.

0

Когда пользователь выбирает любую ячейку, а затем в файле didSelectRowAtIndexPath вы можете добавить выбранный объект динамически.

[someMutableArr addObject:[tableArr objectAtIndex:indexPath.row]]; 
+0

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

0

Попробуйте

- (void)onButtonClick { 

    int numberOfSections = [tableView numberOfSections]; 

    for (int section = 0; section < numberOfSections; section++) { 

     int numberOfRows = [tableView numberOfRowsInSection:section]; 

     for (int row = 0; row < numberOfRows; row++) { 

      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section]; 
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

      if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 

       // Cell is selected 
       //here you can add that values into an array 
      } else { 

       // Cell is not selected 
      } 
     } 
    } 
} 
+0

как я могу сохранить выбранные строки в массиве ??? –

1

вы можете попробовать настраиваемое действие в UITableView камере кнопки prees, вы можете также использовать поставить флажок изображения и нажмите кнопку вы можете изменить изображение в зарегистрированном здесь код

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{ 
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"identifire"]; 
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifire"] autorelease]; 
    cell.detailTextLabel.text=[id_Array objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.hidden=YES; 
    button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    NSString *path1 = [[NSBundle mainBundle] pathForResource:@"n_cross" ofType:@"png"]; 
    UIImage *buttonImage1 = [[UIImage alloc] initWithContentsOfFile:path1]; 
    [button setImage:buttonImage1 forState:UIControlStateNormal]; 
    [button addTarget:self 
       action:@selector(customActionPressed:) 
    forControlEvents:UIControlEventTouchDown]; 
    [button setTitle:@"Custom Action" forState:UIControlStateNormal]; 
    button.frame = CGRectMake(245.0f, 20.0f, 40.0f, 40.0f); 
    [cell addSubview:button]; 
    [buttonImage1 release]; 
     CGRect imageFrame=CGRectMake(10,8,50,50); 
     self.cellimage=[[[UIImageView alloc] initWithFrame:imageFrame] autorelease]; 
     self.cellimage.image=[imageIdArray objectAtIndex:indexPath.row]; 
     [cell.contentView addSubview:self.cellimage]; 
     return cell; 
} 
-(void)customActionPressed :(id)sender 
{ 
//Get the superview from this button which will be our cell 
UITableViewCell *owningCell = (UITableViewCell*)[sender superview]; 
NSIndexPath *cell = [_tableView indexPathForCell:owningCell]; 
NSString *uid=[id_Array objectAtIndex:cell.row]; 
[id_Array removeObjectAtIndex:cell.row]; 
[_tableView reloadData]; 
[self performSelectorInBackground:@selector(ignoreRequest:) withObject:uid]; 
} 

здесь я иметь id_Array и при выборе ячейки я просто удалить объект по этому индексу

Смежные вопросы