在didSelectRowAtIndexPath访问自定义标签属性

Oh *_*Boy 6 iphone objective-c

我在cellForRowAtIndexPath的每个单元格都有一个UILabel.

UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
cellLabel.text = myString;
Run Code Online (Sandbox Code Playgroud)

我想使用indexpath在didSelectRowAtIndexPath访问该字符串"myString".

NSString *anotherString = cell.textLabel.text;
Run Code Online (Sandbox Code Playgroud)

返回null.

现在,如果在cellForRowAtIndexPath,我做了类似cell.textLabel.text = theString;的事情,didSelectRowAtIndexPath返回适当的单元格.

我的问题是,如何在didSelectRowAtIndexPath中访问我应用于单元格的UILabel中的文本?

此外,在didSelectRowAtIndexPath中记录单元格将返回 cell: <UITableViewCell: 0x5dcb9d0; frame = (0 44; 320 44); autoresize = W; layer = <CALayer: 0x5dbe670>>

编辑:

    NSString *myString = [[results objectAtIndex:indexPath.row] valueForKey:@"name"];
//cell.textLabel.text = myString;

CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
CGFloat height = 20;
CGRect frame = CGRectMake(10.0f, 10.0f, width, height);

UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
cellLabel.text = myString;
cellLabel.textColor = [UIColor blackColor];
cellLabel.backgroundColor = [UIColor whiteColor];
cellLabel.textAlignment = UITextAlignmentLeft;
cellLabel.font = [UIFont systemFontOfSize:14.0f];
[cell.contentView addSubview:cellLabel];
[cellLabel release];

return cell;
Run Code Online (Sandbox Code Playgroud)

Mat*_*ong 18

在这行代码中:

NSString *anotherString = cell.textLabel.text;
Run Code Online (Sandbox Code Playgroud)

你是如何获得这个细胞的?它没有?此外,您正在访问的textLabel字段是UITableViewCell中的默认标签,而不是您在-cellForRowAtIndexPath中添加的标签.以下是从-didSelectRowAtIndexPath获取单元格的方法:

- (void)tableView:(UITableView *)tv 
                 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tv cellForRowAtIndexPath:indexPath];

}
Run Code Online (Sandbox Code Playgroud)

但是,此时的问题是您无法按名称访问UILabel,但是,如果您设置了标记,则可以访问它.因此,在创建UILabel时,请将标记设置为:

UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
cellLabel.text = myString;
cellLabel.textColor = [UIColor blackColor];
cellLabel.backgroundColor = [UIColor whiteColor];
cellLabel.textAlignment = UITextAlignmentLeft;
cellLabel.font = [UIFont systemFontOfSize:14.0f];

// Set the tag to any integer you want
cellLabel.tag = 100;

[cell.contentView addSubview:cellLabel];
[cellLabel release];
Run Code Online (Sandbox Code Playgroud)

那么,现在您可以通过标记访问UILabel:

- (void)tableView:(UITableView *)tv 
          didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tv cellForRowAtIndexPath:indexPath];

    UILabel *label = (UILabel*)[cell viewWithTag:100];

    NSLog(@"Label Text: %@", [label text]);
}
Run Code Online (Sandbox Code Playgroud)