【问题标题】:UITextView, sizeToFit is acting weirdlyUITextView,sizeToFit 行为怪异
【发布时间】:2014-03-24 19:03:53
【问题描述】:

我正在尝试创建一个简单的聊天应用程序以供练习。我使用 UITableView 来设置我的聊天室,并从情节提要中配置了我的单元格。我将一个简单的 UITextView 作为我的消息容器,但是由于某些奇怪的原因,我得到的尺寸很奇怪而且毫无意义。这是单元格的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatroomTableViewCell *cell = (ChatroomTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:@"MessageCell" forIndexPath:indexPath];
    Message *cellMessage = [self.messages objectAtIndex:indexPath.row];

    cell.userNameLabel.text = cellMessage.userName;
    cell.messageLabel.text = cellMessage.messageText;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm a"];
    [cell.messageLabel.layer setCornerRadius:2.0f];

    if (cellMessage.messageType == SENT_MESSAGE) {
        NSString *dateLabelString = [NSString stringWithFormat:@"Sent: %@", [formatter stringFromDate:cellMessage.relevantDate]];
        cell.relevantDateLabel.text = dateLabelString;
        cell.userNameLabel.textAlignment = NSTextAlignmentRight;
        cell.relevantDateLabel.textAlignment = NSTextAlignmentRight;
        [cell.messageLabel setBackgroundColor:self.currentTheme.sentMessageColor];
        [cell.messageLabel.layer setBorderColor:self.currentTheme.sentMessageColor.CGColor];
        [cell.messageLabel setTextAlignment:NSTextAlignmentRight];
        [cell.messageLabel sizeToFit];
        [cell.messageLabel setFrame:CGRectMake(self.view.frame.size.width - 20 - cell.messageLabel.frame.size.width - 10, cell.messageLabel.frame.origin.y, cell.messageLabel.frame.size.width + 10, cell.messageLabel.frame.size.height + 5)];
    } else {
        NSString *dateLabelString = [NSString stringWithFormat:@"Received: %@", [formatter stringFromDate:cellMessage.relevantDate]];
        cell.relevantDateLabel.text = dateLabelString;
        cell.userNameLabel.textAlignment = NSTextAlignmentLeft;
        cell.relevantDateLabel.textAlignment = NSTextAlignmentLeft;
        if (cellMessage.messageType == EVENT_MESSAGE) {
            [cell.messageLabel setBackgroundColor:self.currentTheme.eventMessageColor];
        } else {
            [cell.messageLabel setBackgroundColor:self.currentTheme.receivedMessageColor];
        }
        [cell.messageLabel sizeToFit];
    }
    return cell;
}

这是我得到的结果: 有人熟悉这个问题吗?有谁知道原因吗?

编辑:我尝试使用 UILabel,一切正常,但 UILabel 没有我需要的功能。

【问题讨论】:

    标签: ios uitableview uitextview sizetofit


    【解决方案1】:

    问题是 sizeToFit 没有做,对于 UITextView,你想要做的。您可以制作一个根据其内容调整大小的 UITextView,但这不是这样做的。

    搜索堆栈溢出,你会发现很多信息。例如:How do I size a UITextView to its content?

    【讨论】:

    • 感谢您的回答。只是出于好奇,你知道为什么它的形状像图中的那样吗?
    • @user1563544 如果答案对您有用,请养成投票并接受它的习惯。这将鼓励其他人回答您的问题
    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多