Cadena atribuida con fuentes personalizadas en storyboard no se carga correctamente


Estamos usando fuentes personalizadas en nuestro proyecto. Funciona bien en Xcode 5. En Xcode 6, funciona en texto plano, cadena atribuida en código. Pero esas cadenas atribuidas establecidas en storyboard revertirán a Helvetica cuando se ejecutan en simulador o dispositivo, aunque se ven bien en storyboard.

No estoy seguro si es un error de Xcode 6 o iOS 8 SDK, o la forma de usar fuentes personalizadas se cambia en Xcode 6 / iOS 8?

Author: Black Frog, 2014-09-19

14 answers

La solución para mí fue usar una clase IBDesignable:

import UIKit

@IBDesignable class TIFAttributedLabel: UILabel {

    @IBInspectable var fontSize: CGFloat = 13.0

    @IBInspectable var fontFamily: String = "DIN Light"

    override func awakeFromNib() {
        var attrString = NSMutableAttributedString(attributedString: self.attributedText)
        attrString.addAttribute(NSFontAttributeName, value: UIFont(name: self.fontFamily, size: self.fontSize)!, range: NSMakeRange(0, attrString.length))
        self.attributedText = attrString
    }
}

Dándole esto en el Creador de interfaces:

Fuente personalizada de Interface Builder con cadena atribuida

Puede configurar su attributedstring como lo hace normalmente, pero tendrá que configurar su fontsize y fontfamily una vez más en las nuevas propiedades disponibles.

Como el Creador de interfaces está trabajando con la fuente personalizada de forma predeterminada, esto resulta en un lo que ves es lo que obtienes, que prefiero al compilar aplicaciones.

Nota

La razón por la que estoy usando esto en lugar de solo la versión simple es que estoy configurando propiedades en la etiqueta atribuida como el espacio de línea, que no están disponibles cuando se usa el estilo simple.

 27
Author: Antoine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-12 07:47:57

La respuesta más simple para la que funcionó es arrastrar las fuentes a FontBook. Si las fuentes están en su proyecto pero no en el FontBook de su computadora, IB a veces tiene problemas para encontrarla. Raro, pero ha funcionado para mí en varias ocasiones.

 21
Author: Alan Scarpa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-09 16:13:09

Gracias a este hilo, he llegado a esta solución:

private let fontMapping = [
    "HelveticaNeue-Medium": "ITCAvantGardePro-Md",
    "HelveticaNeue": "ITCAvantGardePro-Bk",
    "HelveticaNeue-Bold": "ITCAvantGardePro-Demi",
]

func switchFontFamily(string: NSAttributedString) -> NSAttributedString {
    var result = NSMutableAttributedString(attributedString: string)
    string.enumerateAttribute(NSFontAttributeName, inRange: NSRange(location: 0, length: string.length), options: nil) { (font, range, _) in
        if let font = font as? UIFont {
            result.removeAttribute(NSFontAttributeName, range: range)
            result.addAttribute(NSFontAttributeName, value: UIFont(name: fontMapping[font.fontName]!, size: font.pointSize)!, range: range)
        }
    }
    return result
}
 5
Author: rexsheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-29 03:26:51

Se encontró con el mismo problema: el atributo font set para TextView en storyboard no funcionó en tiempo de ejecución con XCode 6.1 y iOS 8 SDK.

Así es como resolví este problema, podría ser una solución alternativa para usted:

  1. Abra el inspector de atributos de su textview, cambie el texto a "Simple"

  2. Haga clic en la cruz para eliminar el "wC hR" (rojo abajo)

    introduzca la descripción de la imagen aquí

  3. Cambie el texto a "Atribuido", y luego puede establecer la fuente y el tamaño para su texto.

  4. ejecutar para comprobar si funciona
 4
Author: Zhihao Yang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-30 14:36:14

Mi solución es un poco de trabajo. La solución real es que Apple arregle Interface Builder.

Con él puede marcar todo el texto en negrita y cursiva en interface builder utilizando una fuente del sistema, luego en tiempo de ejecución renderizar su fuente personalizada. Puede no ser óptimo en todos los casos.

 NSMutableAttributedString* ApplyCustomFont(NSAttributedString *attributedText,
                     UIFont* boldFont,
                     UIFont* italicFont,
                     UIFont* boldItalicFont,
                     UIFont* regularFont)
{

    NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc] initWithAttributedString:attributedText];
    [attrib beginEditing];
    [attrib enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrib.length) options:0
                    usingBlock:^(id value, NSRange range, BOOL *stop)
    {
        if (value)
        {
            UIFont *oldFont = (UIFont *)value;
            NSLog(@"%@",oldFont.fontName);

            [attrib removeAttribute:NSFontAttributeName range:range];

            if([oldFont.fontName rangeOfString:@"BoldItalic"].location != NSNotFound && boldItalicFont != nil)
                [attrib addAttribute:NSFontAttributeName value:boldItalicFont range:range];
            else if([oldFont.fontName rangeOfString:@"Italic"].location != NSNotFound && italicFont != nil)
                [attrib addAttribute:NSFontAttributeName value:italicFont range:range];
            else if([oldFont.fontName rangeOfString:@"Bold"].location != NSNotFound && boldFont != nil)
                [attrib addAttribute:NSFontAttributeName value:boldFont range:range];
            else if(regularFont != nil)
                [attrib addAttribute:NSFontAttributeName value:regularFont range:range];
        }
    }];
    [attrib endEditing];

    return attrib;
}

Inspirado por este post

 4
Author: KidA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:24

Puede agregar fuentes personalizadas al libro de fuentes.

Step1 : Haga clic en administrar fuentes. Abre el libro de fuentes.

introduzca la descripción de la imagen aquí

Step2 : Haga clic en más y agregue sus fuentes.

introduzca la descripción de la imagen aquí

La próxima vez que haga clic en la fuente con texto atribuido nueva fuente añadida también se mostrará en la lista. Pero asegúrese de que su fuente personalizada agregada en info.plist y bundle recursos.

 4
Author: mahbaleshwar hegde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 18:21:32

Encontró el mismo problema: la fuente de atributo para UILabel en storyboard no funcionó en tiempo de ejecución. Usando este UIFont + IBCustomFonts.m funciona para mí https://github.com/deni2s/IBCustomFonts

 2
Author: Praveen Sevta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-15 10:25:45

El mismo problema.

Resuelto: Simplemente marque seleccionable en TextView. Sin esto tengo fuente estándar del sistema.

 1
Author: Maselko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-24 08:54:27

He tenido problemas con este error: UILabel se muestra correctamente en IB con fuente personalizada, pero no se muestra correctamente en el dispositivo o simulador (la fuente se incluye en el proyecto y se usa en etiquetas UIL).

Finalmente se encontró el Creador de cadenas atribuidas en la Tienda de aplicaciones (Mac). Genera código para colocarlo en su aplicación en el lugar apropiado. Fantastico. No soy el creador, solo un usuario feliz.

 1
Author: ghr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 07:20:09

Haga doble clic e instale la fuente en el sistema. Funcionará (Xcode 8.2)

 1
Author: Ishara Meegahawala,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-29 05:28:39

Estaba tratando de obtener celdas de vista de tabla con texto que tiene varios párrafos. Las cadenas atribuidas parecían ser una forma de obtener espacio adicional entre los párrafos (algo un poco más bonito que hacer dos líneas de alimentación en la cadena). Me encontré con esta y otras publicaciones cuando descubrí que la configuración de IB no se aplicaba en tiempo de ejecución cuando querías poner un texto diferente en la celda.

Lo principal que se me ocurrió fue agregar una extensión a String (usando Swift) para crear un cadena atribuida con ciertas características. El ejemplo aquí usa la fuente Marker Felt, ya que es fácilmente distinguible de Helvetica. El ejemplo también muestra un poco más de espacio entre los párrafos para hacerlos más distintos entre sí.

extension String {
func toMarkerFelt() -> NSAttributedString {
    var style = NSMutableParagraphStyle()
    style.paragraphSpacing = 5.0
    let markerFontAttributes : [NSObject : AnyObject]? = [
        NSFontAttributeName : UIFont(name: "Marker Felt", size: 14.0)!,
        NSParagraphStyleAttributeName: style,
        NSForegroundColorAttributeName : UIColor.blackColor()
    ]
    let s = NSAttributedString(string: self, attributes: markerFontAttributes)
    return s
    }
}

Luego, en mi TableViewCell personalizado, le envías el texto que deseas y lo convierte en una cadena atribuida en la etiqueta UILabel.

//  MarkerFeltCell.swift
class MarkerFeltCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
func configureCellWithString(inputString : String) {
    myLabel.attributedText = inputString.toMarkerFelt()
}}

En el controlador de vista con la vista de tabla, debe registrar su celda en viewDidLoad () used Usé un plumín, así que algo como:

let cellName = "MarkerFeltCell"
tableView.registerNib(UINib(nibName: cellName, bundle: nil), forCellReuseIdentifier: cellName)

Para que la celda averigüe qué tan alta debe ser, haga una celda prototipo que se use para obtener información de tamaño, y nunca se agregue a la vista de tabla. Por lo tanto, en su ver variables del controlador:

var prototypeSummaryCell : MarkerFeltCell? = nil

Luego en (probablemente anular - dependiendo de su controlador de vista) heightForRowAtIndexPath:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // ...
    if xib == "MarkerFeltCell" {
            if prototypeCell == nil {
                prototypeCell = tableView.dequeueReusableCellWithIdentifier(xib) as? MarkerFeltCell
            }
            let width : CGFloat = tableView.bounds.width
            let height : CGFloat = prototypeCell!.bounds.height
            prototypeCell?.bounds = CGRect(x: 0, y: 0, width: width, height: height)
            configureCell(prototypeCell!, atIndexPath: indexPath)
            prototypeSummaryCell?.layoutIfNeeded()
            let size = prototypeSummaryCell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
            let nextHeight : CGFloat = ceil(size.height + 1.0)
            return nextHeight
    } else {  // ...

En el código anterior, la célula de prototipado se rellenará la primera vez que se necesite. La célula prototypeCell se utiliza entonces para averigüe la altura de la celda después de pasar por el proceso de autosizing. Necesitará redondear la altura con la función ceil (). También agregué un poco de factor de caramelo extra.

El bit de código final es cómo se configura el texto para la celda. Para este ejemplo, simplemente:

func configureCell(cell :UITableViewCell, atIndexPath indexPath: NSIndexPath) {
    if let realCell = cell as? MarkerFeltCell  {
        realCell.configureCellWithString("Multi-line string.\nLine 2.\nLine 3.")    // Use \n to separate lines
    }
}

También, aquí está una toma del plumín. Fija la etiqueta a los bordes de la celda (con el margen deseado), pero utiliza una restricción "Mayor o Igual", con una prioridad menor que" Requerida " para el restricción inferior.

Restricciones de celda

Establece la fuente de la etiqueta en Atribuida. La fuente IB real no importaba.

LabelFont

El resultado en este caso:

Resultados de Cell

 0
Author: anorskdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-26 06:25:33

En caso de cadena atribuida, puede agregar fuente personalizada en la lista de fuentes como - Haga clic en el icono de fuente esto mostrará el siguiente diálogo .En el siguiente diálogo puede agregar su propia categoría o una existente para fuente personalizada.diálogo de fuente atribuida

Después de hacer clic en Administrar fuentes se abre el siguiente cuadro de diálogo seleccionar categoría en la que creó o existente . Haga clic en + signo para añadir la fuente en la categoría. Diálogo Administrar fuente

 0
Author: Sunil Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 07:13:41

Eso es tener una solición simple y rápida y eso es trabajo en mi caso . esa solución es agregar una línea de código en didFinishLaunchingWithOptions func en AppDelegate.archivo swift:

Para TextViews :

UITextView.appearance().font = UIFont(name: "IranSans", size: 17)

Para las etiquetas :

UILabel.appearance().font = UIFont(name: "IranSans", size: 17)

Y para el resto de UIView como este dos {️

 0
Author: Hamid Reza Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-22 20:49:24

La solución @ Hamidptb funciona, asegúrese de obtener el nombre correcto de la fuente (una vez que la haya agregado al libro de fuentes)

  • Abra la aplicación Font Book, navegue hasta su fuente y luego presione Command + I. El nombre PostScript es el nombre de la fuente que desea usar aquí:

    UILabel.apariencia().font = UIFont (nombre: "PostScriptName", tamaño: 17)

 0
Author: itsmcgh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 19:43:08