Name: FormatterKit
Owner: Wire Swiss GmbH
Description: `stringWithFormat:` for the sophisticated hacker set
Forked from: mattt/FormatterKit
Created: 2016-07-14 14:55:53.0
Updated: 2017-12-12 09:53:58.0
Pushed: 2017-01-10 15:22:01.0
Size: 623
Language: Objective-C
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
FormatterKit
is a collection of well-crafted NSFormatter
subclasses for things like units of information, distance, and relative time intervals. Each formatter abstracts away the complex business logic of their respective domain, so that you can focus on the more important aspects of your application.
In short, use this library if you're manually formatting any of the following (with string interpolation or the like):
NSArray
elements in a comma-delimited list (e.g. “Russell, Spinoza & Rawls”)#BADF00D
, rgb(255, 100, 42)
)CLLocationDistance
, CLLocationDirection
, and CLLocationSpeed
in metric or imperial units (eg. “240ft Northwest” / “45 km/h SE”)NSNumber
objects to their ordinal in most major languages (eg. “1st, 2nd, 3rd” / “1ère, 2ème, 3ème”)NSDate
objects (e.g. “3 minutes ago” / “yesterday”)cURL
or Wget
command equivalents for any NSURLRequest
(e.g. curl -X POST "https://www.example.com/" -H "Accept: text/html"
)FormatterKit, along with TransformerKit & InflectorKit provide well-designed APIs for manipulating user-facing content.
FormatterKit comes fully internationalized, with .strings
files for the following locales:
ca
)zh_Hans
)zh_Hant
)cs
)da
)nl
)en
)fr
)de
)el
)he
)hu
)id
)it
)ko
)nb
)nn
)pl
)pt_BR
)ru
)es
)sv
)tr
)uk
)vi
)If you'd like to contribute an additional localization, feel free to open a new pull request.
Because the App Store automatically attempts to determine supported locales, and FormatterKit includes localizations for the aforementioned locales, you may want to remove the .strings
file and .lproj
directory. You can do this most easily by having the following command run in a new Build Phase:
$ find "$TARGET_BUILD_DIR" -maxdepth 8 -type f -name "FormatterKit.strings" -execdir rm -r -v {} \;
If you are using CocoaPods, a seprate localization bundle will be created for the pod. Therefore, App Store won't pick up the extraneous localizations.
Build and run the FormatterKit Example
project in Xcode to see an inventory of the available FormatterKit
components.
Address formats vary greatly across different regions. TTTAddressFormatter
ties into the Address Book frameworks to help your users find their place in the world.
For example, addresses in the United States take the form:
Street Address
City State ZIP
Country
Whereas addresses in Japan follow a different convention:
Postal Code
Prefecture Municipality
Street Address
Country
Requires the
AddressBook
andAddressBookUI
frameworks are included, with#import
statements inPrefix.pch
. Only available on iOS.
ddressFormatter *addressFormatter = [[TTTAddressFormatter alloc] init];
g(@"%@", [addressFormatter stringFromAddressWithStreet:street locality:locality region:region postalCode:postalCode country:country]);
Think of this as a production-ready alternative to NSArray -componentsJoinedByString:
. TTTArrayFormatter
comes with internationalization baked-in, and provides a concise API that allows you to configure for any edge cases.
ray *list = [NSArray arrayWithObjects:@"Russel", @"Spinoza", @"Rawls", nil];
rrayFormatter *arrayFormatter = [[TTTArrayFormatter alloc] init];
ayFormatter setUsesAbbreviatedConjunction:YES]; // Use '&' instead of 'and'
ayFormatter setUsesSerialDelimiter:NO]; // Omit Oxford Comma
g(@"%@", [arrayFormatter stringFromArray:list]); // # => "Russell, Spinoza & Rawls"
RGB, CMYK, and HSL your ROY G. BIV in style. TTTColorFormatter
provides string representations of colors.
olorFormatter *colorFormatter = [[TTTColorFormatter alloc] init];
ring *RGB = [colorFormatter RGBStringFromColor:[UIColor orangeColor]];
When working with CoreLocation
, you can use your favorite unit for distance… so long as your favorite unit is the meter. If you want to take distance calculations and display them to the user, you may want to use kilometers instead, or maybe even miles, if you're of the Imperial persuasion.
TTTLocationFormatter
gives you a lot of flexibility in the display of coordinates, distances, direction, speed, and velocity. Choose Metric or Imperial, cardinal directions, abbreviations, or degrees, and configure everything else (number of significant digits, etc.), with the associated NSNumberFormatter
.
ocationFormatter *locationFormatter = [[TTTLocationFormatter alloc] init];
cation *austin = [[CLLocation alloc] initWithLatitude:30.2669444 longitude:-97.7427778];
cation *pittsburgh = [[CLLocation alloc] initWithLatitude:40.4405556 longitude:-79.9961111];
g(@"%@", [locationFormatter stringFromDistanceAndBearingFromLocation:pittsburgh toLocation:austin]);
2,000 km Southwest"
ationFormatter.numberFormatter setMaximumSignificantDigits:4];
ationFormatter setBearingStyle:TTTBearingAbbreviationWordStyle];
ationFormatter setUnitSystem:TTTImperialSystem];
g(@"%@", [locationFormatter stringFromDistanceAndBearingFromLocation:pittsburgh toLocation:austin]);
1,218 miles SW"
ationFormatter setBearingStyle:TTTBearingNumericStyle];
g(@"%@ at %@", [locationFormatter stringFromSpeed:25],[locationFormatter stringFromBearingFromLocation:pittsburgh toLocation:austin]);
25 mph at 310°"
ationFormatter.numberFormatter setUsesSignificantDigits:NO];
g(@"%@", [locationFormatter stringFromLocation:austin]);
30.2669444, -97.7427778)
TTTNameFormatter
formats names according to the internationalization standards of the AddressBook framework, which determine, for example, the display order of names and whether or not to delimit components with whitespace.
TTTNameFormatter
is not available on OS X.
ameFormatter *nameFormatter = [[TTTNameFormatter alloc] init];
ring *frenchName = [nameFormatter stringFromPrefix:nil firstName:@"Guillaume" middleName:@"François" lastName:@"Antoine" suffix:@"Marquis de l'Hôpital"];
g(@"%@", frenchName);
Guillaume François Antoine Marquis de l'Hôpital"
ring *japaneseName = [nameFormatter stringFromFirstName:@"??" lastName:@"?"];
g(@"%@", japaneseName);
???"
NSNumberFormatter
is great for Cardinal numbers (17, 42, 69, etc.), but it doesn't have built-in support for Ordinal numbers (1st, 2nd, 3rd, etc.)
A naïve implementation might be as simple as throwing the one's place in a switch statement and appending “-st”, “-nd”, etc. But what if you want to support French, which appends “-er”, “-ère”, and “-eme” in various contexts? How about Spanish? Japanese?
TTTOrdinalNumberFormatter
supports English, Spanish, French, German, Irish, Italian, Japanese, Dutch, Portuguese, Simplified Chinese and Swedish. For other languages, you can use the standard default, or override it with your own. For languages whose ordinal indicator depends upon the grammatical properties of the predicate, TTTOrdinalNumberFormatter
can format according to a specified gender and/or plurality.
rdinalNumberFormatter *ordinalNumberFormatter = [[TTTOrdinalNumberFormatter alloc] init];
inalNumberFormatter setLocale:[NSLocale currentLocale]];
inalNumberFormatter setGrammaticalGender:TTTOrdinalNumberFormatterMaleGender];
mber *number = [NSNumber numberWithInteger:2];
g(@"%@", [NSString stringWithFormat:NSLocalizedString(@"You came in %@ place!", nil), [ordinalNumberFormatter stringFromNumber:number]]);
Assuming you've provided localized strings for “You came in %@ place!“, the output would be:
Nearly every application works with time in some way or another, and most often when we display temporal information to users, it's in relative terms to the present. So “3 minutes ago”, “10 months ago”, or “last month”.
iOS 4 introduced a -doesRelativeDateFormatting
property for NSDateFormatter
, but it falls back on an absolute time representation if no idiomatic expression is found. Instead, TTTTimeIntervalFormatter
defaults to a smart relative display of an NSTimeInterval
value, with options to extend that behavior to your particular use case.
imeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];
eIntervalFormatter stringForTimeInterval:0]; // "just now"
eIntervalFormatter stringForTimeInterval:-100]; // "1 minute ago"
eIntervalFormatter stringForTimeInterval:-8000]; // "2 hours ago"
urn idiomatic deictic expressions on / off
eIntervalFormatter stringForTimeInterval:-100000]; // "1 day ago"
eIntervalFormatter setUsesIdiomaticDeicticExpressions:YES];
eIntervalFormatter stringForTimeInterval:-100000]; // "yesterday"
ustomize the present tense deictic expression for
eIntervalFormatter setPresentDeicticExpression:@"seconds ago"];
eIntervalFormatter stringForTimeInterval:0]; // "seconds ago"
xpand the time interval for present tense
eIntervalFormatter stringForTimeInterval:-3]; // "3 seconds ago"
eIntervalFormatter setPresentTimeIntervalMargin:10];
eIntervalFormatter stringForTimeInterval:-3]; // "seconds ago"
No matter how far abstracted from its underlying hardware an application may be, there comes a day when it has to communicate the size of a file to the user.
TTTUnitOfInformationFormatter
transforms a number of bits or bytes and into a humanized representation, using either SI decimal or IEC binary unit prefixes.
nitOfInformationFormatter *unitOfInformationFormatter = [[TTTUnitOfInformationFormatter alloc] init];
tOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "56 bytes"
isplay in either bits or bytes
tOfInformationFormatter setDisplaysInTermsOfBytes:NO];
tOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "416 bits"
se IEC Binary prefixes (base 2 rather than SI base 10; see http://en.wikipedia.org/wiki/IEC_60027)
tOfInformationFormatter setUsesIECBinaryPrefixesForCalculation:NO];
tOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:8660]]; // "8.66 Kbit"
tOfInformationFormatter setUsesIECBinaryPrefixesForCalculation:YES];
tOfInformationFormatter setUsesIECBinaryPrefixesForDisplay:YES];
tOfInformationFormatter stringFromNumberOfBits:[NSNumber numberWithInteger:416]]; // "8.46 Kibit"
NSURLRequest
objects encapsulate all of the information made in a network request, including url, headers, body, etc. This isn't something you'd normally want to show to a user, but it'd be nice to have a way to make it more portable for debugging.
Enter TTTURLRequestFormatter
. In addition to formatting requests simply as POST http://www.example.com/
, it will also generate cURL
and Wget
commands with all of its headers and data fields intact to debug in the console.
tableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/"]];
uest setHTTPMethod:@"POST"];
uest addValue:@"text/html" forHTTPHeaderField:@"Accept"];
URLRequestFormatter cURLCommandFromURLRequest:request];
curl -X POST "https://www.example.com/" -H "Accept: text/html"
FormatterKit is available under the MIT license. See the LICENSE file for more info.