Programmieren mit Swift - Für macOS und iOS
Programmieren mit Swift - Für macOS und iOS
Zeichnen von Text

Auch Text lässt sich direkt auf einem NSView ausgeben. Dafür benötigt man nur zwei Dinge: Den auszugebenden NSString und dessen Position.
NSString *helloString = @"Hallo Welt";
NSPoint textPoint = NSMakePoint(
5, 5);
[helloString drawAtPoint:textPoint withAttributes:
nil];
Wie Sie sehen, ist es sehr einfach, aber genau so sieht der Text anschliessend auch aus. Ganz einfach. Sogar die zuvor gesetzte Farbe hat keine Auswirkungen auf den Text. Diese steuern nämlich die Attribute, die für diesen Text aber nicht angegeben wurden.
NSString *helloString = @"Hallo Welt";
NSPoint textPoint = NSMakePoint(
5, 5);

NSMutableDictionary *textAttrib = [[NSMutableDictionary alloc] init];
[textAttrib setObject:[NSFont fontWithName:
@"Times" size:40]
 forKey:NSFontAttributeName];
[textAttrib setObject:[NSColor purpleColor] forKey:NSForegroundColorAttributeName];

[helloString drawAtPoint:textPoint withAttributes:textAttrib];
stacks_image_0C8D6E75-8E6A-4F32-9725-0F5CA6CCAE64
Benötigt man noch komplexeren Text, sollte man zum Typ NSMutableAttributedString greifen. Mit diesem Typ können innerhalb einer Zeichenkette unterschiedliche Schriftarten und Farben verwendet werden, die dann durch eine NSRange festgelegt werden.
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]
     initWithString:
@"Cocoa lernen Schritt für Schritt"];

[attribString addAttribute:NSFontAttributeName
   
                 value:[NSFont fontWithName:@"Arial" size:20]
                     range:NSMakeRange(0,6)];

[attribString addAttribute:NSForegroundColorAttributeName
                     value:[NSColor redColor]
                     range:NSMakeRange(0,6)];

[attribString addAttribute:NSFontAttributeName
                     value:[NSFont fontWithName:@"Times" size:30]
                     range:NSMakeRange(6,7)];

[attribString addAttribute:NSForegroundColorAttributeName
                     value:[NSColor blueColor]
                     range:NSMakeRange(6,7)];

[attribString addAttribute:NSFontAttributeName
                     value:[NSFont fontWithName:@"Arial" size:18]
                     range:NSMakeRange(13,19)];

[attribString addAttribute:NSUnderlineStyleAttributeName
                     value:[NSNumber numberWithInt:2]
                     range:NSMakeRange(13,19)];

[attribString addAttribute:NSForegroundColorAttributeName
                     value:[NSColor blackColor]
                     range:NSMakeRange(13,19)];

NSPoint textPoint2 = NSMakePoint(
22, 150);
[attribString drawAtPoint:textPoint2];
stacks_image_C2DAF12D-453C-464F-9E2E-3497B3EED4C5