给定是一个带有x个字符数的(html)字符串. String将格式化成一个归因的String.然后显示在UILabel.
UILabel具有> = 25和< = 50的高度,以将行数限制为2. 由于字符串的字符在格式化的归因字符串中不可见,如< b> /< i>,最佳方法是限制归因的字符串的字符数.
UILabel属性.lineBreakMode = .byTruncatingTail导致单词被剪切.
如果人物数量超过UILabel的空间限制,那么这个目标就是在单词间切换.所需maxCharacterCount = 50.确定maxCharacterCount之前的最后一个空格.剪切字符串并追加…作为UILabel的最后一个字符.
限制角色的最佳方法是什么?帮助非常欣赏.
从整个字符串和已知的两行标签高度及其已知宽度开始,并将字符从字符串的末尾继续保留,直到字符串的高度小于标签的高度.然后再剪一个字,以达到最佳效果,追加省略号,并将生成的字符串放入标签中.
这样我就得到了:
注意“时间”之后的词从不开始;我们用插入的省略号在精确的字尾停止.这是我这样做的:
lab.numberOfLines = 2 let s = "Little poltergeists make up the principle form of material " + "manifestation. Now is the time for all good men to come to the " + "aid of the country." let atts = [NSFontAttributeName: UIFont(name: "Georgia",size: 18)!] let arr = s.components(separatedBy: " ") for max in (1..<arr.count).reversed() { let s = arr[0..<max].joined(separator: " ") let attrib = NSMutableAttributedString(string: s,attributes: atts) let height = attrib.boundingRect(with: CGSize(width:lab.bounds.width,height:10000),options: [.usesLineFragmentOrigin],context: nil).height if height < lab.bounds.height { let s = arr[0..<max-1].joined(separator: " ") + "…" let attrib = NSMutableAttributedString(string: s,attributes: atts) lab.attributedText = attrib break } }
当然,对于什么构成一个“单词”和在测量的条件来说,这是可以复杂得多的,但是上面的例子显示了这种事情的一般常用技术,并且足以让你开始.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。