Set Max number of lines to NSMutableAttributedString

Viewed 1993

I am using two NSMutableAttributedString and making one NSMutableAttributedString from that two. I want to limit the different number of max lines for both attributedString. I searched a lot but nothing found working and a good option.

let linkTitleAttributed = NSMutableAttributedString(string: message.getLinkTitle() ?? "" , attributes: [NSFontAttributeName: UIFont.systemFontOfSize(19.0)])
//linkTitleAttributed should be maximum 2 lines.

let linkDescAttributed = NSAttributedString(string: message.getLinkDescription() ?? "", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
//linkDescAttributed should be maximum 5 lines.

 let finalAttributed = NSMutableAttributedString()
        final.append(linkTitleAttributed)
        final.append(linkDescAttributed)

If the text is more then given a number of lines then it should be ending with 'Lorem Ipsum is simply dummy text...'

One solution is in my mind(set text to textview independenty and get visible range ) but I am looking for a better one. Thanks.

1 Answers

You have to process the strings for your title and description and then create a new NSAttributedString. Something like:

func limitNumLines(_ msg: String, max: Int) -> String{
    if max <= 0 { return "" }

    let lines = msg.components(separatedBy: "\n")

    var output = ""
    for i in 0..<max {
        output += lines[i] + "\n"
    }
    return output
}

let titleMessage = "LINE1\nLINE2\nLINE3\nLINE4"
let descMessage = "line1\nline2\nline3\nline4\nline5\nline6"

//linkTitleAttributed (that is, message) should be maximum 2 lines.
let title = limitNumLines(titleMessage, max: 2)
let linkTitleAttributed = NSMutableAttributedString(string: title , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 19.0)])

//linkDescAttributed should be maximum 5 lines.
let desc = limitNumLines(descMessage, max: 5)
let linkDescAttributed = NSAttributedString(string: desc , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)])


let finalAttributed = NSMutableAttributedString()
finalAttributed.append(linkTitleAttributed)
finalAttributed.append(linkDescAttributed)
Related