source: releases/Pester/1.1b1/Source/NSString-NJRExtensions.m@ 535

Last change on this file since 535 was 53, checked in by Nicholas Riley, 22 years ago

Updated for Pester 1.1a5 (very limited release).

Pester 1.1a4 was never released.

File size: 2.9 KB
Line 
1//
2// NSString-NJRExtensions.m
3// Pester
4//
5// Created by Nicholas Riley on Mon Dec 16 2002.
6// Copyright (c) 2002 Nicholas Riley. All rights reserved.
7//
8
9#import "NSString-NJRExtensions.h"
10
11@implementation NSString (NJRExtensions)
12
13- (NSAttributedString *)attributedStringWithFont:(NSFont *)font;
14{
15 return [[[NSAttributedString alloc] initWithString: self attributes: [NSDictionary dictionaryWithObject: font forKey: NSFontAttributeName]] autorelease];
16}
17
18- (NSAttributedString *)underlined;
19{
20 return [[[NSAttributedString alloc] initWithString: self attributes: [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: NSSingleUnderlineStyle] forKey: NSUnderlineStyleAttributeName]] autorelease];
21}
22
23- (NSAttributedString *)small;
24{
25 return [self attributedStringWithFont: [NSFont systemFontOfSize: [NSFont smallSystemFontSize]]];
26}
27
28- (NSAttributedString *)smallBold;
29{
30 return [self attributedStringWithFont: [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]]];
31}
32
33+ (NSString *)ellipsisString;
34{
35 static NSString *ellipsis = nil;
36 if (ellipsis == nil) {
37 const unichar ellipsisChar = 0x2026;
38 ellipsis = [[NSString alloc] initWithCharacters: &ellipsisChar length: 1];
39 }
40 return ellipsis;
41}
42
43@end
44
45@implementation NSMutableString (NJRExtensions)
46
47- (void)truncateToLength:(unsigned)maxLength by:(NSLineBreakMode)method;
48{
49 if ([self length] > maxLength) {
50 NSRange range = {0, [self length] - maxLength};
51 switch (method) {
52 case NSLineBreakByTruncatingHead:
53 range.location = 0;
54 break;
55 case NSLineBreakByTruncatingMiddle:
56 range.location = maxLength / 2;
57 break;
58 case NSLineBreakByTruncatingTail:
59 range.location = maxLength;
60 break;
61 default:
62 range.location = maxLength;
63 break;
64 }
65 [self replaceCharactersInRange: range withString: [NSString ellipsisString]];
66 }
67}
68
69- (void)truncateToWidth:(float)maxWidth by:(NSLineBreakMode)method withAttributes:(NSDictionary *)attributes;
70{
71 if ([self sizeWithAttributes: attributes].width > maxWidth) {
72 float width;
73 int min = 0, max = [self length], avg;
74 NSMutableString *original = [self mutableCopy];
75 while (max >= min) {
76 avg = (max + min) / 2;
77 [self truncateToLength: avg by: method];
78 width = [self sizeWithAttributes: attributes].width;
79 if (width > maxWidth) {
80 max = avg - 1; // too wide
81 } else if (width == maxWidth) {
82 break;
83 } else {
84 min = avg + 1; // too narrow
85 [self setString: original];
86 }
87 }
88 if (width != maxWidth)
89 [self truncateToLength: max by: method];
90 [original release];
91 }
92}
93
94@end
Note: See TracBrowser for help on using the repository browser.