tutorial que framework iphone cocoa-touch uikit

iphone - que - ¿Cómo calcular el ancho de una cadena de texto de una fuente específica y tamaño de fuente?



que es uikit ios (8)

Tengo un UILabel que muestra algunos caracteres. Como "x", "y" o "rpm". ¿Cómo puedo calcular el ancho del texto en la etiqueta (no indica todo el espacio disponible)? Esto es para el diseño automático, donde otra vista tendrá un rectángulo más grande si UILabel tiene un texto más pequeño dentro. ¿Existen métodos para calcular el ancho del texto cuando se especifica un UIFont y un tamaño de fuente? Tampoco hay salto de línea y solo una línea.


Basado en la excelente respuesta de Glenn Howes , creé una extensión para calcular el ancho de una cuerda. Si está haciendo algo así como establecer el ancho de un UISegmentedControl , esto puede establecer el ancho según la cadena de título del segmento.

extension String { func widthOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSFontAttributeName: font] let size = self.size(attributes: fontAttributes) return size.width } func heightOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSFontAttributeName: font] let size = self.size(attributes: fontAttributes) return size.height } }

uso:

// Set width of segmentedControl let starString = "⭐️" let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16 segmentedController.setWidth(starWidth, forSegmentAt: 3)

Swift 4

func widthOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSAttributedStringKey.font: font] let size = self.size(withAttributes: fontAttributes) return size.width } func heightOfString(usingFont font: UIFont) -> CGFloat { let fontAttributes = [NSAttributedStringKey.font: font] let size = self.size(withAttributes: fontAttributes) return size.height } func sizeOfString(usingFont font: UIFont) -> CGSize { let fontAttributes = [NSAttributedStringKey.font: font] return self.size(withAttributes: fontAttributes) }


Como sizeWithFont está en desuso, solo voy a actualizar mi respuesta original para usar Swift 4 y .size

//: Playground - noun: a place where people can play import UIKit if let font = UIFont(name: "Helvetica", size: 24) { let fontAttributes = [NSAttributedStringKey.font: font] let myText = "Your Text Here" let size = (myText as NSString).size(withAttributes: fontAttributes) }

El tamaño debe ser el tamaño en pantalla de "Your Text Here" en los puntos.


Esta simple extensión en Swift funciona bien.

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

Uso:

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


Esto es para la versión 2.3 rápida. Puedes obtener el ancho de la cuerda.

var sizeOfString = CGSize() if let font = UIFont(name: "Helvetica", size: 14.0) { let finalDate = "Your Text Here" let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works sizeOfString = (finalDate as NSString).sizeWithAttributes(fontAttributes) }


Para Swift 3.0+

extension String { func SizeOf_String( font: UIFont) -> CGSize { let fontAttribute = [NSFontAttributeName: font] let size = self.size(attributes: fontAttribute) // for Single Line return size; } }

Úselo como ...

let Str = "ABCDEF" let Font = UIFont.systemFontOfSize(19.0) let SizeOfString = Str.SizeOfString(font: Font!)


Para Swift 4.2

func SizeOf_String( font: UIFont) -> CGSize { let fontAttribute = [NSAttributedStringKey.font: font] let size = self.size(withAttributes: fontAttribute) // for Single Line return size; }

No probado aún ...


sizeWithFont: ahora está en desuso, use sizeWithAttributes: lugar:

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


Puede hacer exactamente eso a través de los diversos métodos sizeWithFont: en NSString UIKit Additions . En su caso, la variante más simple debería ser suficiente (ya que no tiene etiquetas de varias líneas):

NSString *someString = @"Hello World"; UIFont *yourFont = // [UIFont ...] CGSize stringBoundingBox = [someString sizeWithFont:yourFont];

Hay varias variaciones de este método, ej. algunos consideran modos de salto de línea o tamaños máximos.