NSAttributedString tail truncation in UILabel
Asked Answered
R

3

34

I'm using ContextLabel to parse @ , # and URL's. This is the best solution i found, cause it sizes correctly and dont affect performance. It firstly parses string at input and than converts it to NSAttributedString and after this assigns it to attributedText property of UILabel. Everything works as expected, except tail truncation - it's very incorrect ( see pic below )

enter image description here

Where shall i start digging - is it wrong attributes on attributed string? Or label layout issue? Thanks!

Robinett answered 13/5, 2016 at 10:34 Comment(1)
Are you hard coding the width of that label?Happen
H
81

I had this problem and fixed it by adding a NSParagraphStyle specifying the desired line break mode:

    //assuming myString is an NSMutableAttributedString
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byTruncatingTail

    let range = NSRange(location: 0, length: myString.mutableString.length)
    myString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)

See Word wrap for NSMutableAttributedString for further reference.

Hardening answered 30/1, 2017 at 21:25 Comment(0)
K
22

Following also works irrespective of using AttributedText or normal text.
Make sure to add the below line after setting the AttributedText and font to the label:

label.lineBreakMode = .byTruncatingTail
Kurrajong answered 10/1, 2018 at 11:33 Comment(1)
You made my day! Thanks. Keyword - AFTERPerilous
H
1
func htmlToAttributedString() -> NSAttributedString?
    {
        guard let data = data(using: .utf8) else { return nil }
        do
        {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .left
            paragraphStyle.lineBreakMode = .byTruncatingTail
            
            
            let content = try NSMutableAttributedString(data: data, options: [.documentType:     NSAttributedString.DocumentType.html, .characterEncoding:     String.Encoding.utf8.rawValue], documentAttributes: nil)
            
            content.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle,
                                   NSAttributedString.Key.font: UIFont(name:"Poppins-Medium",size:18),
                                   NSAttributedString.Key.foregroundColor: UIColor(red: (94.0/255.0), green: (90.0/255.0), blue: (90.0/255.0), alpha: 1.0)],
                                  range: NSMakeRange(0, content.length))
            
            return content
        }
        catch
        {
            return nil
        }
    }
Hort answered 6/12, 2022 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.