自定义标签Cell的didSelectRowAtIndexPath

Ani*_*nil 5 objective-c uitableview ios

我正在使用此方法添加UILabel到我UITableView和它的工作正常,但我还需要创建一个方法来选择行并保存到临时字符串.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                             reuseIdentifier:CellIdentifier];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
    [cell.contentView addSubview:label];
    label.text = [tableArr objectAtIndex:indexPath.row];
    label.font = [UIFont fontWithName:@"Whitney-Light" size:20.0];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.当我使用cell.textLabel而不是自定义标签时,它工作得很好.

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

    UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *lbltemp = cell1.textLabel;

    _parent.labelone.text = lbltemp.text;       
}
Run Code Online (Sandbox Code Playgroud)

Wai*_*ain 10

您可以创建自己的UITableViewCell子类,以便获得对标签的引用(并防止您在单元格上创建多个标签).或者你可以使用这样的标签:

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

    if (cell = nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                         reuseIdentifier:CellIdentifier];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
        label.tag = 123123;
        [cell.contentView addSubview:label];
    }

    UILabel *label = (UILabel *)[cell viewWithTag:123123];
    label.text = [tableArr objectAtIndex:indexPath.row];
    label.font = [UIFont fontWithName:@"Whitney-Light" size:20.0];

    return cell;
}

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

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *label = (UILabel *)[cell viewWithTag:123123];

    _parent.labelone.text = label.text;       
}
Run Code Online (Sandbox Code Playgroud)

您的原始代码是添加新标签,但随后尝试从默认标签中获取文本...它还始终创建一个新单元格并为其添加新标签,这非常浪费.

此外,您通常不应该在标签中存储文本,您应该真正tableArr去获取文本.标记方法更适合在重复使用单元格时更新标签,或者如果您让用户编辑文本(在a中UITextField).