zoukankan      html  css  js  c++  java
  • 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( 228, height: 1000), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)
            print(size)
            label.frame = CGRect(x: 50, y: 250,  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.

  • 相关阅读:
    教你三招打入App Store推荐目录!
    APP下载量低 如何显著提高APP下载量?
    导致APP排名下跌的主要因素
    如何提高APP关键词覆盖率?先熟悉套路!
    如何让你的ASO优化效果提升10倍?
    有效的移动应用推广策略
    APP运营推广不得不看的6种数据指标
    如何为你的APP选出“最好”的关键词
    手机应用开发宝典:如何养成一款畅销APP
    Linux下设置定期执行脚本
  • 原文地址:https://www.cnblogs.com/doudouyoutang/p/15796928.html
Copyright © 2011-2022 走看看