Swift 计算字符串展示的区域

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

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/

- (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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章