2015-12-21 3 views
-1

Я работаю над uipicker внутри uitableview's prototype cell где я создаю uilabel. Теперь я добавляю выбранное значение строки выбора выбора на ярлыке, но моя проблема заключается в том, что когда я выбираю строку из представления выбора, все метки обновляются.Как добавить значение uipickerview выбранного значения строки в uilabel?

Значение должно быть обновлено в выбранной строке на uilabel. Вот мой код и снятый снимок экрана.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return [myData count]; 
} 

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath]; 

    UILabel *lable = (UILabel*)[cell viewWithTag:111]; 
    lable.tag = indexPath.row; 
    lable.text = value; 
    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
    _nameLabel.text =nil; 

    [self.mytableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO]; 

    [self bringUpPickerViewWithRow:indexPath]; 
} 



- (void)bringUpPickerViewWithRow:(NSIndexPath*)indexPath 
{ 
    UITableViewCell *currentCellSelected = [self.mytableview cellForRowAtIndexPath:indexPath]; 
    [UIView animateWithDuration:1.0f 
          delay:0.0f 
         options:UIViewAnimationOptionCurveEaseInOut 
        animations:^ 
    { 
     self.pickerView.hidden = NO; 
     self.pickerView.center = (CGPoint) { currentCellSelected.frame.size.width/2, self.mytableview.frame.origin.y + currentCellSelected.frame.size.height*4}; 


     self.mytableview.separatorStyle = UITableViewCellSeparatorStyleNone; 
     [self.mytableview setNeedsDisplay]; 
    } 
        completion:nil]; 


} 

- (void)hidePickerView 
{ 
    [UIView animateWithDuration:1.0f 
          delay:0.0f 
         options:UIViewAnimationOptionCurveEaseInOut 
        animations:^ 
    { 
     self.pickerView.center = (CGPoint){160, 800}; 
    } 
        completion:^(BOOL finished) 
    { 
     self.pickerView.hidden = YES; 
     [self.mytableview reloadData]; 
    }]; 
} 


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{ 
    return 1; 
} 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component 
{ 
    return _countingarray.count; 
} 



- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component 
{ 

    [self.mytableview reloadData]; 
    [self hidePickerView]; 
    NSLog(@"row selected:%ld", (long)row); 
    NSString *resultString = _countingarray[row]; 

    value = resultString; 
} 


- (NSString*) pickerView:(UIPickerView *)pickerView titleForRow: (NSInteger)row forComponent:(NSInteger)component 
{ 
    //return [NSString stringWithFormat:@"%d", row+1]; 
    return _countingarray[row]; 
} 

- (IBAction)editbuttonclicked:(id)sender { 

    if([self.mytableview isEditing] == NO){ 

     //[self.mytableview settitle:@"Done"]; 
     //set the table to editing mode 
     [self.mytableview setEditing:YES animated:YES]; 
    }else 

    { 

     //we are currently in editing mode 
     //change the button text back to Edit 
     //[self.editbutton setTitle:@"Edit"]; 
     //take the table out of edit mode 
     [self.mytableview setEditing:NO animated:YES]; 
    } 
} 

-(void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if (editingStyle == UITableViewCellEditingStyleDelete) { 

     [myData removeObjectAtIndex:indexPath.row]; 
     [self.mytableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
    } 
} 

this is my screen shot when i select 2 from picker view at first cell than all the uilabel updates same value

+0

кто-то помочь мне плз –

+0

у вас уже есть 'myData', который вы используете чтобы определить, сколько строк должно отображаться в таблицеView, вам, вероятно, нужно, чтобы все, что находится в этом массиве, определяло текст, показанный для каждой метки. После того, как вы это сделали, вам больше нужно «значение», но после этого нужно будет обрабатывать данные в этом массиве и «reloadData». – luk2302

+0

как объявляется значение? –

ответ

0

Вот вещь. «Значение» является глобальным переменным, поэтому, когда вы перезагрузите вид таблицы, этот код вызывается для каждой ячейки в Tableview

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath]; 

UILabel *lable = (UILabel*)[cell viewWithTag:111]; 
lable.tag = indexPath.row; 
lable.text = value; 
return cell; 
} 

Теперь обратите внимание

label.text= value 

Для каждой ячейки наклейки получить одинаковое значение (независимо от это).

@ luk2302 является правильным. Управляйте этим внутри себя myData.

Предлагаемое решение Для этого может быть множество способов. Это то, что я могу предложить сразу

Не имеет значения как глобальной переменной. Добавьте NSIndexPath * currentCellPath как глобальную переменную.

Теперь у вас didSelectRow сделать это

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath 
    { 
    currentCellPath = indexPath; 
    // remaining code goes here 
    _nameLabel.text =nil; 

    [self.mytableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO]; 

    [self bringUpPickerViewWithRow:indexPath]; 
    } 

Теперь в didselectRow вашего сборщика сделать это

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component 
{ 
UITableViewCell *cell = [self.myTableView cellForIndexPath:currentCellPath]; 
cell.label.text = _countingarray[row]; 
    [self.mytableview reloadData]; 
    [self hidePickerView]; 
    NSLog(@"row selected:%ld", (long)row); 
    //NSString *resultString = _countingarray[row]; // remove this 

    //value = resultString; //romove this 

}

+0

его дает мне ошибку для tableview и метки следующим образом: - «Нет видимого интерфейса для uitableview объявляет селектор cellforindexpath». и другая ошибка для таблицы; - «метка свойства не найдена на объекте типа« uitableviewcell ». –

+0

мой плохой, первый использование '[self.myTableView cellForRowAtIndexPath: currentCellPath] ' – ibnetariq

+0

и, пожалуйста, сообщите мне, почему вам нужно назначить вам тег Label (111) и изменить его indexPath. – ibnetariq

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