给定是一个带有x个字符的(html)字符串.String将被格式化为属性String.然后显示在UILabel
.
在UILabel
具有的高度>= 25
和<= 50
到行数限制为2.
由于String具有在格式化的属性String中不可见的字符,例如<b> / <i>
,最好的方法是限制属性String的字符数.
UILabel
财产.lineBreakMode = .byTruncatingTail
导致词语被削减.
我们的目标,如果字符数将超过在空间的限制UILabel
,是词与词之间切断.渴望maxCharacterCount = 50
.确定space
之前的最后一个maxCharacterCount
.剪切字符串并追加...
为最后一个字符UILabel
.
限制角色的最佳方法是什么?帮助非常感谢.
mat*_*att 11
从完整的字符串和标签的已知双线高度及其已知宽度开始,并在字符串末端保留切割字,直到在该宽度处,字符串的高度小于标签的高度.然后在末尾再剪一个单词以获得良好的度量,附加省略号,并将得到的字符串放入标签中.
就这样,我得到了这个:
请注意,"时间"之后的单词永远不会开始; 我们用插入的省略号停在一个精确的单词结尾处.这是我如何做到的:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当然,可能是很多关于什么是"字",用于测量的条件更复杂,但上述说明了一般常用的技术为这样的事情,应该足以让你开始.
import UIKit
class ViewController: UIViewController {
var str = "Hello, playground"
var thisInt = 10
@IBOutlet weak var lbl: UILabel!
var lblWidth : CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lblWidth = lbl.bounds.width
while str.characters.count <= thisInt - 3 {
str.remove(at: str.index(before: str.endIndex))
str.append("...")
}
lbl.text = str
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)