Access custom label property at didSelectRowAtIndexPath

后端 未结 2 1402
日久生厌
日久生厌 2021-02-09 15:12

I have a UILabel for each cell at cellForRowAtIndexPath.

UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
cellLabel.text = myString;

相关标签:
2条回答
  • 2021-02-09 16:06

    Can you post the code that you assign the cellLabel to the cell? Did you do something like this: cell.textLabel = cellLabel?

    Look for UITableViewCell for more details

    0 讨论(0)
  • 2021-02-09 16:12

    In this line of code:

    NSString *anotherString = cell.textLabel.text;
    

    How are you obtaining the cell? Is it nil? Also, the textLabel field you're accessing is the default label in the a UITableViewCell and not the label you are adding in -cellForRowAtIndexPath. Here is how you can get the cell from -didSelectRowAtIndexPath:

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

    The issue at this point, though, is that you can't access the UILabel by name, however, you can access it if you've set a tag. So, when you create your UILabel, set the tag like this:

    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];
    

    So, now you can access the UILabel by tag:

    - (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]);
    }
    
    0 讨论(0)
提交回复
热议问题