Swift 计算字符串展示的区域

一、如果是普通文本,那么可以采用NSString的方法,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import UIKit
import PlaygroundSupport
 
class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
 
        let label = UILabel()
        label.text = "永和九年,岁在癸丑,暮春之初,会于会稽山阴之兰亭,修稧(禊)事也。群贤毕至,少长咸集。此地有崇山峻领(岭),茂林修竹;又有清流激湍,映带左右,引以为流觞曲水,列坐其次。虽无丝竹管弦之盛,一觞一咏,亦足以畅叙幽情。是日也,天朗气清,惠风和畅。仰观宇宙之大,俯察品类之盛。所以游目骋怀,足以极视听之娱,信可乐也。"
        label.textColor = .black
        label.layer.borderColor = UIColor.red.cgColor
        label.layer.borderWidth = 1.0
        let font = UIFont.systemFont(ofSize: 16.0)
        label.font = font
 
        let size = (label.text! as NSString).boundingRect(with: CGSize(width: 228, height: 1000), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)
        print(size)
        label.frame = CGRect(x: 50, y: 250, width: size.size.width, height: size.size.height)
        label.numberOfLines = 0
        view.addSubview(label)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrectwithsize

如果是富文本, 同样是类似的方法,https://developer.apple.com/documentation/foundation/nsattributedstring/1529154-boundingrectwithsize/

1
2
3
- (CGRect)boundingRectWithSize:(CGSize)size
                       options:(NSStringDrawingOptions)options
                       context:(NSStringDrawingContext *)context;

但是,文档中提示,返回的bounds是浮点数,需要采用向上取整的方式,避免采用这个尺寸后文字容纳不下

Discussion

You can use this method to compute the space required to draw the string. The constraints you specify in the size parameter are a guide for the renderer for how to size the string. However, the actual bounding rectangle returned by this method can be larger than the constraints if additional space is needed to render the entire string. Typically, the renderer preserves the width constraint and adjusts the height constraint as needed.

In iOS 7 and later, this method returns fractional sizes (in the size component of the returned rectangle); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.

 

posted @   兜兜有糖的博客  阅读(117)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示