2014-03-24 34 views
0

我正在尝试为实践创建一个简单的聊天应用程序。我使用UITableView来设置我的聊天室,并从故事板中配置我的单元格。我把一个简单的UITextView作为我的消息容器,然而由于一些奇怪的原因,我得到的尺寸很奇怪,没有任何意义。这里是该小区的代码:UITextView,sizeToFit行事怪异

- (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; 
} 

这是结果我得到: enter image description here 是任何人都熟悉这个问题?有谁知道原因?

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

回答

0

问题是,sizeToFit不会这样做,对于UITextView,你想做什么。您可以制作一个尺寸与其内容相同的UITextView,但这不是如何去做的。

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

+0

谢谢您的回答。出于好奇,你知道为什么它的形状像在图片中吗? – user1563544

+0

@ [user1563544](http://stackoverflow.com/users/1563544/user1563544)如果答案对您有用,然后养成投票并接受它的习惯。这会鼓励其他人回答你的问题 –