我正在使用SlackTextViewController构建一个聊天视图,我花了一天时间来改进视觉效果,使其更加现代化。但是,heightForRowAtIndexPath
无法正确计算消息中文本的高度。来自朋友的用户接收的消息具有专用于他们的屏幕宽度的70%,其中一部分被降级为32x32的化身。我认为问题源于titleBounds和BodyBounds。
我有两组独立的变量用于用户发送和用户接收的消息。因此检查“测试自我”。
let message = self.messages[indexPath.row]
var defaultFontSize = MessageCell.defaultFontSize
var minimumHeight = MessageCell.kMessageTableViewCellMinimumHeight
var avatarHeight = MessageCell.kMessageTableViewCellAvatarHeight
if message.username == "Test Self" {
defaultFontSize = SelfMessageCell.defaultFontSize
minimumHeight = SelfMessageCell.kMessageTableViewCellMinimumHeight
avatarHeight = 0
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .ByWordWrapping
paragraphStyle.alignment = .Left
let pointSize = defaultFontSize
let attributes = [
NSFontAttributeName : UIFont.systemFontOfSize(pointSize),
NSParagraphStyleAttributeName : paragraphStyle
]
var width = (CGRectGetWidth(tableView.frame) * 0.7) - avatarHeight
width -= 25.0
let titleBounds = (message.username as NSString).boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
let bodyBounds = (message.messageContents as NSString).boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
if message.messageContents.characters.count == 0 {
return 0
}
var height = CGRectGetHeight(titleBounds)
height += CGRectGetHeight(bodyBounds)
if height < minimumHeight {
height = minimumHeight
}
return height
这是UITableViewCell的代码
override func layoutSubviews() {
super.layoutSubviews()
let width = self.bounds.width * 0.3
chatBubble.frame = CGRectMake(34, 23, self.bounds.width - 36 - width, self.bounds.height - 28)
usernameLabel.frame = CGRectMake(4, 5, chatBubble.frame.size.width - 8, 16)
messageLabel.frame = CGRectMake(20,4,chatBubble.frame.size.width - 28,chatBubble.frame.size.height - 4)
avatarView.frame = CGRectMake(2, self.bounds.height - 30, 32, 32)
}
这是init()
chatBubble = UIImageView(frame: CGRectZero)
chatBubble.contentMode = .ScaleToFill
chatBubble.image = UIImage(named: "ChatBubble")
contentView.addSubview(chatBubble)
usernameLabel = UILabel(frame: CGRectZero)
usernameLabel.font = UIFont(name: "HelveticaNeue-Light", size: 16)
usernameLabel.textAlignment = .Left
usernameLabel.textColor = UIColor.grayColor()
contentView.addSubview(usernameLabel)
messageLabel = UILabel(frame: CGRectZero)
messageLabel.font = UIFont(name: "HelveticaNeue", size: 16)
messageLabel.numberOfLines = 0
messageLabel.lineBreakMode = .ByWordWrapping
messageLabel.textAlignment = .Left
messageLabel.textColor = UIColor.blackColor()
chatBubble.addSubview(messageLabel)