OStack程序员社区-中国程序员成长平台

标题: ios - UITableView 单元格内容未正确显示 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 06:14
标题: ios - UITableView 单元格内容未正确显示

我使用自动布局并希望显示具有自定义单元格的 UITableView,该单元格的 UITextView 具有可变内容。

单元格显示如下。对于聊天消息,第一次显示单元格时单行仅显示 2-3 个字符,并且下一个字符被强制转到下一行。但是,当我滚动 tableView 以使这些单元格不可见并向后滚动以使它们可见时(我这样做是为了当它们再次可见时 cellForRowAtIndexPath: 再次调用方法来渲染单元格),它们会正确渲染单元格,如图所示第二张图片。

enter image description here enter image description here

代码:

- (NSInteger)numberOfSectionsInTableViewUITableView *)tableView
{
    return 1;
}

- (NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section
{
    return [chatData count];
}

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    RS_User *user = [[RS_User alloc]init];
    chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];
    NSUInteger row = indexPath.row;
    cell.chatCellBackground.image = nil;

        NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT];       // get text string(message) from array

        cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
        UIFont *font = [UIFont systemFontOfSize:FONT_SIZE];
        cell.textString.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE];        // set text font
        cell.textString.text = chatText;

        // set text
        CGSize size = [cell.textString.text sizeWithFont:cell.textString.font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        cell.textString.frame = ...;
        [cell.textString sizeToFit];

        NSDate *theDate = [[chatData objectAtIndex:row] objectForKeyATE];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormatATE_FORMAT];
        NSString *timeString = [formatter stringFromDate:theDate];
        cell.timeLabel.text = timeString;                                             // set timeLabel to display date and time
        cell.timeLabel.font = [UIFont fontWithName:FONT_NAME size:SMALL_FONT_SIZE];

        cell.userLabel.text = @"Name";//[[chatData objectAtIndex:row] objectForKey:NAME];       // set userLabel to display userName

        CGSize size1 = [cell.userLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];

        // check cell contains sender name or receiver name
        if (thisCellIsForSender)
        {
            // Set bubble for sender
            cell.chatCellBackground.image = [[UIImage imageNamed"bubbleMine.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
            cell.chatCellBackground.frame = ...;
        }
        else
        {
            // set bubble for receiver
            cell.chatCellBackground.image = [[UIImage imageNamed"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
            cell.chatCellBackground.frame = ...;
        }

    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    return cell;
}

- (CGFloat)tableViewUITableView *)tableView heightForRowAtIndexPathNSIndexPath *)indexPath
{
    RS_User *user = [[RS_User alloc]init];
    chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];
    NSUInteger row = indexPath.row;
    cell.chatCellBackground.image = nil;

    NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT];       // get text string(message) from array

    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    UIFont *font = [UIFont systemFontOfSize:FONT_SIZE];
    cell.textString.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE];        // set text font
    cell.textString.text = chatText;

    // set text
    CGSize size = [cell.textString.text sizeWithFont:cell.textString.font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
    cell.textString.frame = ...;
    [cell.textString sizeToFit];

    NSDate *theDate = [[chatData objectAtIndex:row] objectForKeyATE];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormatATE_FORMAT];
    NSString *timeString = [formatter stringFromDate:theDate];
    cell.timeLabel.text = timeString;                                             // set timeLabel to display date and time
    cell.timeLabel.font = [UIFont fontWithName:FONT_NAME size:SMALL_FONT_SIZE];

    cell.userLabel.text = [[chatData objectAtIndex:row] objectForKey:NAME];       // set userLabel to display userName

    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];

    CGSize size1 = [cell.userLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];

    // check cell contains sender name or receiver name
        if (thisCellIsForSender)
        {
            // Set bubble for sender
            cell.chatCellBackground.image = [[UIImage imageNamed"bubbleMine.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
            cell.chatCellBackground.frame = ...;
        }
        else
        {
            // set bubble for receiver
            cell.chatCellBackground.image = [[UIImage imageNamed"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
            cell.chatCellBackground.frame = ...;
        }

    cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    return cell.bounds.size.height;        
}

更新:我可以从 coverback 的回答中解决一些问题。静止单元格布局不正确。我正在为单元格中每个 UI 对象的约束添加照片。

用户名:

enter image description here enter image description here

时间戳:

enter image description here enter image description here

聊天消息:

enter image description here enter image description here

气泡图:

enter image description here enter image description here

单元格布局:

enter image description here

你发现约束有什么问题吗?你可以问我分析约束是否困难。



Best Answer-推荐答案


结合thandasoru和coverback的答案解决了我的问题。下面是我使用的代码。

我在自定义 UITableViewCell 的类中添加了以下方法。

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat maxTextWidth = [UIScreen mainScreen].bounds.size.width * 0.40;
    self.userLabel.preferredMaxLayoutWidth = maxTextWidth;
    self.chatMessage.preferredMaxLayoutWidth = maxTextWidth;
    self.timeLabel.preferredMaxLayoutWidth = self.timeLabel.frame.size.width;
    [super layoutSubviews];
}

UITableView 数据源方法:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    CustomCell * cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier"customCellId"];
    // Set all label's text and image to ImageView
    ...

    // Update layout
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
}

- (CGFloat)tableViewUITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    customCell * cell = (customCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];

    NSString * userName = cell.userLabel.text;
    NSString * chatText = cell.chatMessage.text;

    // Get bounding rect of userName label
    CGRect userNameFrame = [userName boundingRectWithSize:CGSizeMake(maxLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes{NSFontAttributeName:cell.userLabel.font} context:nil];

    // Get bounding rect of chatMessage label
    CGRect chatTextFrame = [chatText boundingRectWithSize:CGSizeMake(maxLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes{NSFontAttributeName:cell.chatMessage.font} context:nil];

    // Calculate cell height from its contents
    height = userNameFrame.size.height + chatTextFrame.size.height + PADDING_ABOVE_TOP_LABEL + DISTANCE_BETWEEN_TWO_LABELS + PADDING_BELOW_BOTTOM_LABEL;

    return height;

关于ios - UITableView 单元格内容未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21474157/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4