NSAttributedString tail truncation in UILabel

三世轮回 提交于 2019-12-03 14:46:44

问题


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 )

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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/37207762/nsattributedstring-tail-truncation-in-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!