Adjust UILabel height depending on the text

前端 未结 30 1779
走了就别回头了
走了就别回头了 2020-11-22 03:53

Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players m

30条回答
  •  粉色の甜心
    2020-11-22 04:19

    You can implement TableViewController's (UITableViewCell *)tableView:cellForRowAtIndexPath method in the following way (for example) :

    #define CELL_LABEL_TAG 1
    
    - (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *text = @"my long text";
    
        static NSString *MyIdentifier = @"MyIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero  reuseIdentifier:identifier] autorelease];
        }
    
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
        CGFloat height = [self textHeight:text] + 10;
        CGRect frame = CGRectMake(10.0f, 10.0f, width, height);
    
        UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
        cellLabel.tag = CELL_LABEL_TAG;
        cellLabel.textColor = [UIColor blackColor];
        cellLabel.backgroundColor = [UIColor clearColor];
        cellLabel.textAlignment = UITextAlignmentLeft;
        cellLabel.font = [UIFont systemFontOfSize:12.0f];
        [cell.contentView addSubview:cellLabel];
        [cellLabel release];
    
        return cell;
    }
    
    UILabel *label = (UILabel *)[cell viewWithTag:CELL_LABEL_TAG];
    label.text = text;
    label.numberOfLines = 0;
    [label sizeToFit];
    return cell;
    

    Also use NSString's sizeWithFont:constrainedToSize:lineBreakMode: method to compute the text's height.

提交回复
热议问题