OGeek|极客世界-中国程序员成长平台

标题: ios - Swift:如何计算居中字符串的大小 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:48
标题: ios - Swift:如何计算居中字符串的大小

我目前计算字符串的大小,如下所示。如何计算居中字符串?

func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
    return (string as NSString).boundingRect(with: CGSize(width: width, height: Double.greatestFiniteMagnitude),
                                             options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                             attributes: [NSFontAttributeName: font],
                                             context: nil).size
}



Best Answer-推荐答案


你说:

Something else must be effecting the result because the string goes to 2 lines approximately two characters before it is calculated as doing so.

是的,如果你自己渲染 boundingRect 将捕获字符串的大小(例如使用 draw(in:withAttributes。但是 UILabel 可以想象做各种各样的其他事情(从边缘插入等)。

令我震惊的是,您有两个基本选择:

  1. 现在,您可以获取 Collection View 流布局的布局并将其 itemSize 设置为 UICollectionViewFlowLayoutAutomaticSize(在 iOS 10 及更高版本中):

    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
    layout.estimatedItemSize = ...
    

    然后单元格将根据您在单元格中的自动布局约束自动调整大小(例如,标签的固定宽度,允许固有尺寸控制高度,也许尺寸 <= 一些最大尺寸)。

  2. 如果您想自己计算 boundingRect,那么您可能会使用 draw(in:withAttributes 自己渲染它,也避免了 UILabel 在幕后所做的任何特殊行为:

    let string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam quis leo convallis, euismod ipsum sed, lacinia diam. Nam sit amet justo id lacus blandit sodales id et."
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping
    paragraphStyle.alignment = .center
    
    let attributes: [NSAttributedStringKey: Any] = [
        .font: font,
        .paragraphStyle: paragraphStyle
    ]
    
    let rect = string.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                   options: .usesLineFragmentOrigin,
                                   attributes: attributes,
                                   context: nil)
    
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
    string.draw(in: rect, withAttributes: attributes)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    然后您可以将 imagerect 用于 UIImageView

关于ios - Swift:如何计算居中字符串的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46453019/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4