2017-09-27 30 views
1

我目前正在計算字符串的大小,如下所示。我如何對居中字符串進行這種計算?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 
} 
+2

你是什麼意思「居中字符串的大小」?居中的字符串的大小應該與不居中的字符串相同。 – Rob

+0

你絕對正確,@Rob。原諒我我的重要時刻。還有其他的東西必須影響結果,因爲在計算之前,字符串變成兩行約兩個字符。我應該提到該字符串被設置爲標籤的文本,該標籤位於集合視圖單元格中。我提供的寬度是視圖的寬度,小於單元格的左右部分插頁以及標籤的前部和後部空格。 – Jake

回答

0

你說:因爲字符串去2線前約兩個字符是因爲這樣做計算

別的東西必須實現的結果。

是的,boundingRect會,如果你自己(如與draw(in:withAttributes:)使其捕獲字符串的長度,但可以UILabel令人信服地做各種其他的事情(從邊緣insetting等)。

我感到那你有兩個基本的選擇:

  1. 如今,你會把自己的集合視圖流佈局的佈局和設置其itemSizeUICollectionViewFlowLayoutAutomaticSize(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() 
    

    然後,您可以對於UIImageView,使用imagerect

0

目標C版本

UIFont *font = [UIFont fontWithName:@"Helvetica" size:30]; 
NSDictionary *userAttributes = @{NSFontAttributeName: font, 
           NSForegroundColorAttributeName: [UIColor blackColor]}; 
NSString *text = @"hello"; 
... 
const CGSize textSize = [text sizeWithAttributes: userAttributes]; 

夫特版本:

extension String { 
    func size(OfFont font: UIFont) -> CGSize { 
     return (self as NSString).size(attributes: [NSFontAttributeName: font]) 
    } 
} 

用法:

let string = "hello world!" 
let font = UIFont.systemFont(ofSize: 12) 
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32} 
+0

他想要指定最大寬度並以線條換行來計算高度。以上僅適用於單行文本。 – Rob

相關問題