2010-04-03 5 views
5

J'utilise cette catégorie (est-ce pas?) http://www.nightproductions.net/references/dsclickableurltextfield_reference.html#setAttributedStringValueEssayer de créer un lien avec NSTextField

à mettre en œuvre textfields cliquables. J'ai importé le fichier d'en-tête dans ma classe de contrôleur et codez il est attribué la valeur de chaîne comme ce

NSAttributedString* str = [[NSAttributedString alloc] initWithString:@"http://www.yahoo.com"]; 
[url setAttributedStringValue:(NSAttributedString *)str]; 

[str release]; 

Le champ de texte ne peut être sélectionné et non modifiable.

La valeur du champ de texte est définie mais elle n'est pas cliquable et ce n'est pas un lien.

Merci d'avance.

+0

Ajouté tag Cocoa. – hallski

Répondre

9

J'ai trouvé un autre moyen facile d'afficher les liens dans NSTextField. Vous pouvez utiliser le HTML. Voici un court exemple:

-(NSAttributedString *)stringFromHTML:(NSString *)html withFont:(NSFont *)font 
{ 
    if (!font) font = [NSFont systemFontOfSize:0.0]; // Default font 
    html = [NSString stringWithFormat:@"<span style=\"font-family:'%@'; font-size:%dpx;\">%@</span>", [font fontName], (int)[font pointSize], html]; 
    NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding]; 
    NSAttributedString* string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil]; 
    return string; 
} 

Maintenant, vous pouvez appeler la méthode pour le champ texte:

// @property IBOutlet NSTextField *tf; 
[tf setAllowsEditingTextAttributes: YES]; 
[tf setSelectable:YES]; 
NSString *credits = @"Visit our <a href=\"http://www.webpage.com\">webpage</a>"; 
[tf setAttributedStringValue:[self stringFromHTML:credits withFont:[tf font]]]; 
+0

C'est mieux car le curseur se transforme en curseur de doigt, et avec l'autre méthode, la police change lorsqu'on clique dessus. –

Questions connexes