简体   繁体   中英

Can we restrict the width of a NSMutableAttributedString?

I have a string Ex: Arya said "We must find a solution" yesterday. 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. So I added it as 3 different NSMutableAttributedString s appended together and set this to a 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"

  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)

But none of them worked. I want to reproduce the UILabel .lineBreakMode = .byTruncatingTail for a NSMutableAttributedString . Am I doing something wrong here, is there a way to achieve this?

Here is a solution using three UILabel s in a 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)
    ])
}

output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM