uItableviewcell для динамического получения значения - PullRequest
1 голос
/ 26 января 2010

я сделал приложение, которое имеет просмотр изображений для захвата изображения с камеры и кнопку, где нажимается кнопка. PickerView появится в списке действий и выберет тип изображения (jpg, png, bmp ..), один раз выбрав из сборщика название кнопки. будет меняться в зависимости от результата pickerView,

Затем я пытаюсь преобразовать это в UITableView, который имеет 2 раздела (1 для изображения и 1 для выбора типа изображения,

Теперь у меня возникла проблема, когда я пытаюсь выполнить imageView в ячейку, но изображение перекрывает другую ячейку, и после захвата изображения с камеры этот imageView не обновляется, но один раз прокручивает таблицу, а не только обновляется,

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

ниже мой код, может кто-нибудь помочь или улучшить его,

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1; 
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return NSLocalizedString(@"Image", @"");
            break;
        case 1:
            return NSLocalizedString(@"Image type", @"");
            break;
        default:
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
    }

    switch (indexPath.section) {
        case 0:
        {
            UIImageView *abc = [[UIImageView alloc] initWithFrame:CGRectMake(5,5,100,100)];
            abc.image = imageView.image;
            [cell addSubview:abc];
        }
            break;
        case 1:
            cell.textLabel.text = @"- Click here -";
            break;
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease];
    }

    if(indexPath.section == 0) {
        NSLog(@"selected %d",indexPath.section);
    }
    if(indexPath.section == 1) {
        NSLog(@"selected %d",indexPath.section);
        [self chooseType];
    }
}

- (void)chooseType{
    actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                              delegate:self
                                     cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                     otherButtonTitles:nil];

    NSArray *typeObject = [NSArray arrayWithObjects:@".jpg",@".png",@".bmp",nil];

    self.pickerData = typeObject;

    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
    pickerView.delegate = self;
    pickerView.showsSelectionIndicator = YES;

    pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
    [pickerDateToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(TypeDonePick)];
    [barItems addObject:doneBtn];

    [pickerDateToolbar setItems:barItems animated:YES];

    [actionSheet addSubview:pickerDateToolbar];
    [actionSheet addSubview:pickerView];
    [actionSheet showInView:self.view];
    [actionSheet setBounds:CGRectMake(0,0,320, 464)];
    [pickerView release];
    [actionSheet release];  
}


- (void)TypeDonePick
{
    NSInteger row = [pickerView selectedRowInComponent:0];
    titleCause.textColor = [UIColor blackColor];
    titleCause.text = [pickerData objectAtIndex:row];
    NSLog(@" %@ ",titleCause.text);
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

возможно ли изменить тест ячейки вне допустимой функции UITable

спасибо

Ответы [ 2 ]

1 голос
/ 26 января 2010

Ваша проблема в том, что таблица не знает, что ей нужно обновить уже видимые ячейки. для быстрого решения просто добавьте [tableView reloadData] после того, как пользователь выберет изображение / тип изображения, это заставит таблицу воссоздать ячейки и получить от них обновленные данные.

Если вы хотите обновить ячейки по отдельности, вы можете использовать [tableView cellForRowAtIndexPath:], чтобы получить ячейку, которую вы хотите обновить. например,

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    cell.textLabel.text = @"updated text";
    // You might need to call the following function though I'm not sure
    // [cell.textLabel setNeedsDisplay];

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

UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
UIImageView *imageView = [cell viewWithTag:kImageViewTag];
imageView.image = updatedImage;
// Again you might need to tell the image to refresh it self
//[imageView setNeedsDisplay];
0 голосов
/ 10 февраля 2013

Чтобы изменить LabelText UITableViewCell в IndexPath, мы можем использовать код ниже. -> Это работает правильно! (в этом примере я изменяю labelText в строке 0 tableView):

   UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
   cell.textLabel.text = @"updated text";
   // must to write line below to update labelText for row 0
   [tableView setNeedsDisplay];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...