我的想法是做一些像WhatsApp这样的事情,让每个用户左右对齐消息。
我正在尝试此代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = messageTableView.dequeueReusableCellWithIdentifier("messageCell") as! MessageCell
// get the items in this section
let sectionItems = self.getSectionItems(indexPath.section)
// get the item for the row in this section
let currentMessage = sectionItems[indexPath.row]
var messageTextViewAlignment: NSLayoutFormatOptions
if (currentMessage.from == self.currentUserId)
{
messageTextViewAlignment = NSLayoutFormatOptions.AlignAllRight
}
else
{
messageTextViewAlignment = NSLayoutFormatOptions.AlignAllLeft
}
var newConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[messageTextView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["messageTextView": cell.messageTextView])
cell.messageTextView.addConstraints(newConstraint)
return cell
}
答案 0 :(得分:0)
我不确定你想要达到什么目标。将UILabel对齐在屏幕的正确一侧,或者在UILabel
想象一下,您希望将UIlabel
对齐,以便像在What's App中一样,从泡泡中向左或向右移动这个很酷的空白区域。在这里你可以尝试一些事情:
由于您使用IB作为自定义UITableViewCell,似乎只包含该消息,因此您不能只有IBOutlets
来引导UILabel
到单元格contentView
的尾随约束边距。
看起来像是:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelLeadingConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelTrailingConstrain;
并在您的代码中
if (currentMessage.from == self.currentUserId)
{
labelLeadingConstrain = X1;
labelTrailingConstrain = X2;
}
else
{
labelLeadingConstrain = X2;
labelTrailingConstrain = X1;
}
[...]
return cell
}
我不熟悉以这种方式处理的约束,但尝试
if (currentMessage.from == self.currentUserId)
{
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-X1-[constraintUILabel]-X2-|" options:0 metrics:nil views:@{@"constraintUILabel" :cell.messageTextView}]];
}
else
{
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-X2-[constraintUILabel]-X1-|" options:0 metrics:nil views:@{@"constraintUILabel" :cell.messageTextView}]];
}
[...]
return cell
}
此约束至少适用于2个视图。所以有你的messageTextView
并假设你有messageView
包含它(可能是tableViewCell' contentView本身)
[NSLayoutConstraint constraintsWithVisualFormat:@"H:[messageTextView][messageView]" options:NSLayoutFormatAlignAllRight metrics:nil views:@{@"messageTextView" :cell.messageTextView},@"messageView" :cell.messageView}]
在您的代码段中,永远不会使用messageTextViewAlignment
变量,所以我相信您应该使用上面的剪辑(Swift样式)替换NSLayoutFormatAlignAllRight
var
messageTextViewAlignment
答案 1 :(得分:0)
@" NiColas Braun"在问这里之前,我编写了这个解决方案,就像你在#34;使用IB"中所建议的那样,它有效,但我觉得这不是一个好的解决方案:
func alignTextView(textViewAlignment: NSLayoutFormatOptions)
{
horizontalSpaceFromContentViewToTextView.constant = 0
let spaceX = initialTextViewWidth - finalTextViewWidth
if( spaceX > 0 )
{
if (textViewAlignment == NSLayoutFormatOptions.AlignAllRight)
{
horizontalSpaceFromContentViewToTextView.constant = spaceX
}
}
//println("spcaceX: \(spaceX) --- \(messageTextView.text)")
}
我想使用NSLayoutFormatOptions.AlignAllRight和NSLayoutFormatOptions.AlignAllLeft