我正在使用来自核心数据的文本数据来调整消息容器框架的大小,但是如果这有意义的话,框架设置的速度似乎不够快。我尝试将代码放在 override layoutSubviews 和 setupViews 中,但无济于事。
下面是设置messageContainer框架的代码
if let messageText = cell?.text {
let size = CGSize(width: 100, height: 40)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 12)], context: nil)
messageContainer.translatesAutoresizingMaskIntoConstraints = false
messageContainer.frame.size.width = estimatedFrame.width
messageContainer.frame.size.height = estimatedFrame.height
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .left , relatedBy: .equal, toItem: messageContainer, attribute: .left, multiplier: 1, constant: 5))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .width , relatedBy: .lessThanOrEqual, toItem: messageContainer, attribute: .width, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .height , relatedBy: .lessThanOrEqual, toItem: messageContainer, attribute: .height, multiplier: 1, constant: 0))
}
现在文本刚好从屏幕上移开,没有换行。
有什么建议吗?
编辑:我在 messageLabel 后面附上了容器应该是什么样子的屏幕截图。此版本与当前版本之间的区别在于当前版本使用的是自动布局,我认为这是导致问题的原因...
最佳答案
问题:
根据您设置的自动布局系统施加的约束:
messageLabel.width <= messageContainer.width
但这可能不是您想要的。
解决方案:
你的真实意图是限制权利。
- 移除宽度限制。
- 不要设置
messageContainer
的框架,使用约束。 - 在单元格的初始化程序中设置所有这些。
messageLabel.right <= messageContainer.right
代码:
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .right , relatedBy: . lessThanOrEqual, toItem: messageContainer, attribute: .right, multiplier: 1, constant: -5))
注意事项:
请测试它是否符合您的要求。
首选解决方案:
如果能使用下面的就更好了:
关于ios - NSLayoutConstraints 未设置(swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969779/