pietrop.com Rotating Header Image

Cocoa tutorial – NSBadge

Italiano

Italiano

Quante volte avete visto un piccolo cerchietto con una scritta all’interno, disegnato sopra l’icona di un’applicazione presente nel Dock? Ad esempio, Mail notifica il numero di nuovi messaggi (emails e feeds), mentre XCode notifica il numero di errori occorsi durante l’ultima compilazione.

Questo cerchietto è detto “Badge” ed è molto semplice da disegnare, perché richiede soltanto la stringa rappresentata (un numero o delle lettere, poche, ma sempre lettere).

In futuro scriverò un tutorial su come personalizzare tutta l’icona, per poter disegnare, ad esempio, un cursore di caricamento (come nel caso di Photoshop quando processa un qualcosa).

Diamo uno sguardo al codice, e supponiamo di voler disegnare il Badge nel momento in cui viene chiamato il metodo “drawBadge” (può anche avere un nome diverso, come “notifyNumNewEntries” in un client email o “notifyNumErrors” in un IDE):

- (void) drawBadge: (NSString *)aString
{
    //Retrieve the Dock Tile
    NSDockTile *myTile = [NSApp dockTile];
    //Set the Badge string value
    [myTile setBadgeLabel:aString];
}

Di seguito un’immagine che mostra il risultato finale avendo passato a drawBadge: la stringa “pietrop”:

Icon badge

Icon badge

English

English

How many times did you see a little red circle with something written inside appearing on an application’s icon in the Dock? Mail and XCode represent two examples; the first one notifies a certain number of new items incoming and the second one notifies the number of erros occured during the last compilation.

This little red circle is called “Badge”, and it’s very simple to draw, because it comes only with a string. In future I’ll post a tutorial on how to customize the Dock icon and draw something like a “Load in progress bar” (like in Photoshop).

Now, let’s look at the code. Suppose that you want to draw the badge when the method “drawBadge” is called by your application (it can be something else, like “notifyNumNewEntries” in a mail client or ”notifyNumErrors” in a IDE):

- (void) drawBadge: (NSString *)aString
{
    //Retrieve the Dock Tile
    NSDockTile *myTile = [NSApp dockTile];
    //Set the Badge string value
    [myTile setBadgeLabel:aString];
}

Follows an image showing the final result: a badge drawn with the string “pietrop”.

Icon badge

Icon badge

One Comment

  1. Radeksonic scrive:

    This is cool!
    I have made a twitter application and now I use this to display how many new tweets there are. Thanks

Leave a Reply