File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change 1
- # StringCalculate
1
+ # StringCalculate
2
+
3
+ 一种更加方便和高效计算多行Label高度的新方法
4
+
5
+
6
+ 与系统的提供的boundingRect相比,优点主要有以下两点:
7
+
8
+ 1.耗时较少
9
+
10
+ 在Demo和我们实际项目中测试结果中,时间消耗约为系统的boundingRect方法的30%。
11
+
12
+ 2.调用更加方便。
13
+
14
+ 在使用系统的boundingRect方法进行Label高度计算时,通常情况下,我们需要根据最大行数来估算Label最大的高度,类似于这样:
15
+ ```
16
+ let maxLine = 3//最大行数
17
+ let singleLineHeight = 20//单行高度
18
+ let maxHeight = CGFloat(maxLine * singleLineHeight)//计算得到最大宽度
19
+ let rect = text.boundingRect(with: CGSize(width: UIScreen.main.bounds.size.width, height: maxHeight),
20
+ options: .usesLineFragmentOrigin,
21
+ attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16)],
22
+ context: nil).size.width
23
+ ```
24
+ 但是在使用这种新方法计算时,我们只需要指定最大高度就行了,类似于这样:
25
+ ```
26
+ let rect = text.boundingRectFast(withMaxWidth: UIScreen.main.bounds.size.width, font: UIFont.boldSystemFont(ofSize: 16), maxLine: maxLine)
27
+ ```
28
+
29
+
You can’t perform that action at this time.
0 commit comments