2011-05-16 15 views

Respuesta

94

Lo que podría hacer es usar un NSAttributedString .

NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName]; 
NSString *yourString = ...; 
NSRange boldedRange = NSMakeRange(22, 4); 

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString]; 

[attrString beginEditing]; 
[attrString addAttribute:kCTFontAttributeName 
        value:boldFontName 
        range:boldedRange]; 

[attrString endEditing]; 
//draw attrString here... 

Tome un vistazo a this handy dandy guide a dibujar objetos con NSAttributedString Core texto.

+2

¿Alguien puede decirme qué se define como "kCTFontAttributeName"? – Sohan

+0

Vaya. simplemente pensé que es una constante que se define en CTFont.h en su marco CoreText. – Sohan

+8

dice: Uso del identificador indefinido 'kCTFontAttributeName', ¿quiso decir 'NSFontAttributeName'? ¿Qué pasa con eso? ¿Puedo usar NSFontAttributeName en su lugar? – tester

3

Un NSString es solo un contenedor de datos. No contiene ningún detalle sobre las preocupaciones de presentación.

Parece que lo que probablemente quiera hacer es audaz parte del UILabel que se está utilizando para mostrar su cadena. Lo cual no creo que puedas hacer Pero siempre puede dividir la IU en tres etiquetas, una para "Distancia aproximada:", una para "120 m", y una para "distancia". Colóquelos en línea el uno con el otro y obtendrá el efecto deseado.

Otra opción podría ser usar un UIWebView y un poco de margen de beneficio para mostrar su cadena con información de formato embebido, como se discute aquí:

http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview

57

Como mencionó Jacob, es probable que desee utilizar un NSAttributedString o un NSMutableAttributedString. El siguiente es un ejemplo de cómo puedes hacer esto.

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Approximate Distance: 120m away"]; 
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22 

[string beginEditing]; 

[string addAttribute:NSFontAttributeName 
      value:[NSFont fontWithName:@"Helvetica-Bold" size:12.0] 
      range:selectedRange]; 

[string endEditing]; 
+1

Cuando intento esto, obtengo 'Uso del identificador no declarado 'NSFont'' en la línea' value: '. ¿Cómo puedo solucionar esto? – ZuluDeltaNiner

+0

Este es un gran ejemplo. Te falta un '@' alrededor de la cadena de ejemplo después de tu método 'initWithString:' en la primera línea. :) –

+11

@ZuluDeltaNiner Si está usando iOS, reemplace 'NSFont' con' UIFont' –

10

Si no quiere preocuparse por las fuentes (ya que no todos variación de fuente contiene "Bold"), aquí es otra manera de hacerlo. Tenga en cuenta, esto es actualmente sólo está disponible en OS X ...:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"]; 
    [attrString beginEditing]; 
    [attrString applyFontTraits:NSBoldFontMask 
         range:NSMakeRange(22, 4)]; 
    [attrString endEditing]; 
+0

¿NSBoldFontMask no está declarado para iOS? Cualquier reemplazo? – coolcool1994

+0

@ coolcool1994 - Lo siento, no es que yo sepa. Editaré mi respuesta para aclarar que este es solo el truco de OS X ... – yura

2

En ios Xamarin puede negrita dentro de un NSString esta manera:

public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange) 
    { 
     var firstAttributes = new UIStringAttributes { 
      Font = UIFont.BoldSystemFontOfSize(fontSize) 
     }; 

     NSMutableAttributedString boldString = new NSMutableAttributedString (str); 
     boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange)); 
     return boldString; 
    }  

y llamar a este método:

myLabel = new UILabel(); 
... 
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);  
+6

La pregunta no era sobre Xamarin. –

+2

Xamarin funciona con el mismo objeto NSString, la pregunta no especificaba en qué idioma debería estar la respuesta. Vine aquí buscando la sintaxis de Xamarin para hacer esto. Respuesta válida – root

6

El código anterior me dio un error cuando creé UILabel con este attributeString.

que utiliza este código y funcionó:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string]; 
NSRange boldedRange = NSMakeRange(0, 1); 
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:@"Lato-Bold" size:12]; 
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil]; 
[attrString setAttributes:dictBoldText range:boldedRange]; 
+0

Gracias @ Andrew Marin. –

2

me acoplada @Jacob Relkin y respuestas @ Andrew Marin, de lo contrario, tengo los accidentes. Aquí está la respuesta para iOS9:

UIFont *boldFont = [UIFont boldSystemFontOfSize:12]; 
NSString *yourString = @"Approximate Distance: 120m away"; 
NSRange boldedRange = NSMakeRange(22, 4); 

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString]; 

[attrString beginEditing]; 
[attrString addAttribute:NSFontAttributeName 
        value:boldFont 
        range:boldedRange]; 

[attrString endEditing]; 

Me tomó un vistazo a la documentación oficial: 1 y 2.

2

Swift

también incluye recibir el rango de la cadena que desea envalentonar dinámicamente

let nameString = "Magoo" 
let string = "Hello my name is \(nameString)" 

let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black] 
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)] 

let attributedString = NSMutableAttributedString(string: string, attributes: attributes) 

let nsString = NSString(string: string) 
let range = nsString.rangeOfString(nameString) 

if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) } 

someLabel.attributedText = attributedString 
2

Para una cadena negrita y sin codificar su fuente, se puede utilizar el anchoTrazo atributo con un valor negativo :

let s = NSMutableAttributedString(string: "Approximate Distance: 120m away") 
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26)) 
Cuestiones relacionadas