Отправить текст из таблицы в текстовое поле - PullRequest
0 голосов
/ 20 сентября 2011

Мне нужно сделать это: когда пользователь выбирает строку из табличного представления, чтобы отправить текст из этой строки в текстовое поле из другого табличного представления.Например, если я выберу Услуги из http://i55.tinypic.com/t043zk.png

, я хочу увидеть Услуги здесь, рядом с типом Partenaire: http://i56.tinypic.com/10zn43p.jpg

Я попробовал это:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = selectedCell.textLabel.text;

    NSLog(@"%@",cellText);
 self.recherchePartenaireTableView.partenaire.text=cellText;
}

и при нажатии кнопки ok:

-(IBAction)OkButtonPressed:(id)sender{
    NSLog(@"BTN Ok");
    [self.recherchePartenaireTableView.tableviewrecherchepartenaire reloadData];
    [self.navigationController popViewControllerAnimated:YES];
}

, но это не работает.Может кто-нибудь мне помочь?Заранее спасибо.

в файле реализации для первого изображения

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundView.opaque = NO;
        //cell.alpha = 0.65;

        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.opaque = NO;
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.highlightedTextColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:18];

        cell.detailTextLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.opaque = NO;
        cell.detailTextLabel.textColor = [UIColor whiteColor];
        cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    }

    // Set up the cell...
    [[cell textLabel] setText: [typePartenaireArray objectAtIndex:indexPath.row]] ;

    return cell;
}

** в файле реализации для второго изображения **

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

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {

            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            cell.backgroundView.opaque = NO;
            //cell.alpha = 0.65;

            cell.textLabel.backgroundColor = [UIColor clearColor];
            cell.textLabel.opaque = NO;
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.highlightedTextColor = [UIColor whiteColor];
            cell.textLabel.font = [UIFont boldSystemFontOfSize:18];

            cell.detailTextLabel.backgroundColor = [UIColor clearColor];
            cell.detailTextLabel.opaque = NO;
            cell.detailTextLabel.textColor = [UIColor whiteColor];
            cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
            cell.detailTextLabel.font = [UIFont systemFontOfSize:14];

            if(indexPath.row==0)
            {
                partenaire=[[UITextField alloc] init];
                partenaire.frame = CGRectMake(200,10,80,50);
                partenaire.textColor=[UIColor grayColor];
                partenaire.text=@"Tous";     
                [partenaire setKeyboardAppearance:NO];
                [cell.contentView addSubview:partenaire];

            }

        }

        // Set up the cell...
        [[cell textLabel] setText: [arraytableview objectAtIndex:indexPath.row]] ;

        return cell;


}

Ответы [ 2 ]

1 голос
/ 20 сентября 2011

Переопределите метод init второго UITableView, чтобы принять дополнительный аргумент (в вашем случае текст ячейки, выбранной в текущем UITableView). А во втором UITableView, где вы конфигурируете ячейки, задайте их текст по своему усмотрению с помощью этого параметра, который вы только что получили из предыдущего tableView, которому был назначен второй объект табличного представления.

0 голосов
/ 20 сентября 2011

Вы должны вставить свой текст в массив arrayviewview в позиции 1 (массивы начинаются с 0). Убедитесь, что он объявлен как NSMutableArray, иначе вы не сможете его изменить.

Итак, вы должны сделать: [arraytableview insertObject: cellText atIndex: 1] в вашем методе OK. Для этого вам может потребоваться ввести переменную, которая содержит выбранный в данный момент текст, чтобы «перенести» его из выбранного метода в метод OK.

Или вы просто добавляете его в - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath, но затем он сразу добавляет текст, не нажимая OK. действительно зависит от того, что вы хотите

Надеюсь, теперь все ясно.

Код для определения UITableViewCell с несколькими строками, текстовыми полями и т. Д .:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        imageView = [[UIImageView alloc] initWithFrame: CGRectZero];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview: imageView];

        titleLabel = [[UILabel alloc] initWithFrame: CGRectZero];
        [titleLabel setFont:[UIFont systemFontOfSize:14.0]];
        [titleLabel setTextColor:[UIColor blackColor]];
        [titleLabel setHighlightedTextColor:[UIColor darkGrayColor]];
        [titleLabel setLineBreakMode: UILineBreakModeWordWrap];
        titleLabel.numberOfLines = 2;

        [self.contentView addSubview: titleLabel];

        description = [[UITextField alloc] initWithFrame: CGRectZero];
        [description setFont:[UIFont systemFontOfSize:12.0]];
        [description setTextColor:[UIColor darkGrayColor]];
        [description setHighlightedTextColor:[UIColor darkGrayColor]];
        [self.contentView addSubview: description];


    }
    return self;
}

    -(void) layoutSubviews {
        [super layoutSubviews];
        //  D_IN;   
        [imageView setFrame:CGRectMake(8.0, 10.0, 20.0, 20.0)];
        [titleLabel setFrame:CGRectMake(40.0, 1.0, 250.0, 40.0)]; //two lines
        [description setFrame:CGRectMake(40.0, 37.0, 250.0, 3.0)];//not used

        //  D_OUT;  
}

Убедитесь, что компоновка верна при указании начальных x и y для каждого нового компонента, иначе вы ничего не увидите !!!

Тогда просто установите его с помощью

 titleLabel.text = 

или

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