[英]Can we restrict the width of a NSMutableAttributedString?
I have a string Ex: Arya said "We must find a solution" yesterday.我有一个字符串 例如: Arya昨天说“我们必须找到解决方案” 。 Here I want to restrict the width of the text in bold ("We must find a solution") to 100, but others must not be shortened.
这里我想将粗体文本(“我们必须找到解决方案”)的宽度限制为 100,但其他的不得缩短。 So I added it as 3 different
NSMutableAttributedString
s appended together and set this to a UILabel
.所以我将它添加为 3 个不同的
NSMutableAttributedString
附加在一起并将其设置为UILabel
。 I want to know if I can restrict the width of one of these strings alone.我想知道我是否可以单独限制这些字符串之一的宽度。 I tried the following :
我尝试了以下方法:
let mutableString = "We must find a solution"
mutableString.draw(in: CGRect(x: 0, y: 0, width: 100, height: 30))
mutableString.draw(with: CGRect(x: 0, y: 0, width: 10, height: 10), options: .truncatesLastVisibleLine, context: .none)
mutableString.boundingRect(with: CGSize(width: 100, height: 40), options: [.truncatesLastVisibleLine,.usesFontLeading], context: .none)
But none of them worked.但他们都没有工作。 I want to reproduce the
UILabel
.lineBreakMode = .byTruncatingTail
for a NSMutableAttributedString
.我想为
NSMutableAttributedString
重现UILabel
.lineBreakMode = .byTruncatingTail
。 Am I doing something wrong here, is there a way to achieve this?我在这里做错了什么,有没有办法实现这一目标?
Here is a solution using three UILabel
s in a UIStackView
:这是在
UIStackView
使用三个UILabel
的解决方案:
override func viewDidLoad() {
super.viewDidLoad()
let label1 = UILabel()
label1.text = "Arya said"
label1.font = UIFont.italicSystemFont(ofSize: 20.0)
let label2 = UILabel()
label2.text = "\"We must find a solution\""
label2.font = UIFont.boldSystemFont(ofSize: 20.0)
label2.lineBreakMode = .byTruncatingTail
let label3 = UILabel()
label3.text = "yesterday"
label3.font = UIFont.italicSystemFont(ofSize: 20.0)
let stack = UIStackView(arrangedSubviews: [label1, label2, label3])
stack.axis = .horizontal
stack.spacing = 4
label2.translatesAutoresizingMaskIntoConstraints = false
stack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label2.widthAnchor.constraint(equalToConstant: 100)
])
self.view.addSubview(stack)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
])
}
output:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.