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.

 

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