我们可以限制NSMutableAttributedString的宽度吗?

时间:2020-08-27 10:33:08

标签: ios swift uilabel nsmutableattributedstring

我有一个字符串,例如: Arya说 “我们必须找到一个解决方案” 昨天。在这里,我想限制文本以粗体显示(“我们必须找到解决方案”)到100,但其他字符不得缩短。因此,我将其添加为3个不同的NSMutableAttributedString附加在一起,并将其设置为UILabel。我想知道是否可以单独限制其中一个字符串的宽度。 我尝试了以下方法:

let mutableString = "We must find a solution"

  1. mutableString.draw(in: CGRect(x: 0, y: 0, width: 100, height: 30))

  2. mutableString.draw(with: CGRect(x: 0, y: 0, width: 10, height: 10), options: .truncatesLastVisibleLine, context: .none)

  3. mutableString.boundingRect(with: CGSize(width: 100, height: 40), options: [.truncatesLastVisibleLine,.usesFontLeading], context: .none)

但是他们都不起作用。我想为UILabel复制.lineBreakMode = .byTruncatingTail NSMutableAttributedString。我在这里做错什么了,有办法实现吗?

1 个答案:

答案 0 :(得分:1)

这是在UILabel中使用三个UIStackView的解决方案:

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)
    ])
}

输出:

enter image description here

相关问题