我试图让 iPhone 应用程序用户通过设置自定义字体来个性化应用程序。我想知道是否可以将 UIFont 对象保存到 NSUserDefaults。设置字体和字体大小然后保存对象会使事情变得容易得多。代码示例也会很棒。
问问题
1290 次
2 回答
3
我会创建一个类别来隐藏复杂性 - 你可以从这样的开始
。H
// NSUserDefaults+CustomFontAdditions.h
@interface NSUserDefaults (CustomFontAdditions)
- (UIFont *)ps_fontForKey:(NSString *)fontKey;
- (void)ps_setFont:(UIFont *)font forKey:(NSString *)fontKey;
@end
.m
// NSUserDefaults+CustomFontAdditions.m
#import "NSUserDefaults+CustomFontAdditions.h"
NSString * const PSCustomFontsKey = @"PSCustomFontsKey";
NSString * const PSCustomFontKeyFontName = @"PSCustomFontKeyFontName";
NSString * const PSCustomFontKeyFontSize = @"PSCustomFontKeyFontSize";
@implementation NSUserDefaults (CustomFontAdditions)
- (UIFont *)ps_fontForKey:(NSString *)fontKey;
{
NSDictionary *fonts = [self dictionaryForKey:PSCustomFontsKey];
UIFont *font = nil;
if (fonts) {
NSDictionary *fontComponents = [fonts valueForKey:fontKey];
NSString *fontName = [fontComponents valueForKey:PSCustomFontKeyFontName];
CGFloat size = [[fontComponents valueForKey:PSCustomFontKeyFontSize] floatValue];
font = [UIFont fontWithName:fontName size:size];
}
return font;
}
- (void)ps_setFont:(UIFont *)font forKey:(NSString *)fontKey;
{
NSMutableDictionary *fonts = [[self dictionaryForKey:PSCustomFontsKey] mutableCopy];
if (!fonts) {
fonts = [[NSMutableDictionary alloc] initWithCapacity:1];
}
NSDictionary *fontComponents = [[NSDictionary alloc] initWithObjectsAndKeys:
font.fontName, PSCustomFontKeyFontName,
[NSNumber numberWithFloat:font.pointSize], PSCustomFontKeyFontSize, nil];
[fonts setValue:fontComponents forKey:fontKey];
[self setObject:fonts forKey:PSCustomFontsKey];
}
@end
用法看起来像
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults ps_setFont:[UIFont systemFontOfSize:12.0f] forKey:@"font1"];
[standardUserDefaults ps_setFont:[UIFont fontWithName:@"Helvetica Neue" size:24.0f] forKey:@"font2"];
[standardUserDefaults synchronize];
NSLog(@"%@", [standardUserDefaults ps_fontForKey:@"font1"]);
NSLog(@"%@", [standardUserDefaults ps_fontForKey:@"font2"]);
输出:
#=> 2012-04-19 00:01:21.756 ma[1340:f803] <UICFFont: 0x68a18b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 12px
#=> 2012-04-19 00:01:21.765 ma[1340:f803] <UICFFont: 0x6b99670> font-family: "Helvetica Neue"; font-weight: normal; font-style: normal; font-size: 24px
于 2012-04-18T23:05:14.387 回答
2
这些是可以存储在 NSUserDefaults 中的项目:
NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary
你可以这样做:
NSDictionary *fontInformation = [NSDictionary dictionaryWithObjectsAndKeys:
@"YOUR_FONTS_NAME", "fontName",
[NSNumber numberWithInt:14], @"fontSize", nil];
[[NSUserDefaults standardUserDefaults] setObject:fontInformation forKey:@"fontInfo"];
然后稍后您可以从 NSUserDefaults 中获取 NSDictionary 并重新创建 UIFont。
于 2012-04-18T22:50:34.690 回答