我想创建一个设置页面,它从NSUserDefaults设置/获取滑块值(文本大小),但我的应用程序没有。我没有得到任何错误,它只是不想保存。我已经对代码进行了评论,以帮助您更好地理解我想要做的事情,但这很简单。我有一个具有字体大小的7级滑块,您可以简单地滑动它以确定您想要的字体大小 - 这是我想要在整个应用程序中保存的值。但每当我按下导航栏并再次打开设置页面时,默认大小始终为22。
·H
@interface SettingsViewController : UIViewController
@property (strong, nonatomic) IBOutlet UISlider *sizeSlider;
@property (strong, nonatomic) IBOutlet UILabel *sampleText;
@end
的.m
@interface SettingsViewController () {
NSArray *numbers;
NSMutableAttributedString *sampleTextString;
int fontSize;
NSUserDefaults *defaults;
}
@end
@implementation SettingsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"Settings";
numbers = @[@(10), @(12), @(14), @(16), @(18), @(20), @(22)]; // Text Sizes, these number values represent each slider position
NSInteger numberOfSteps = ((float)[numbers count]-1); // Slider values go from 0 to the number of values in your numbers array
self.sizeSlider.maximumValue = numberOfSteps; // As the slider moves it will continously call the -valueChanged:
self.sizeSlider.minimumValue = 0;
defaults = [NSUserDefaults standardUserDefaults]; //Setting the font to be the current font saved in the system
long textsize = [defaults integerForKey:@"fontSize"];
NSLog(@"textsize: %ld", textsize);
self.sizeSlider.value = textsize; // Set the Slider to whatever font you had set it previously
self.sizeSlider.continuous = YES; // NO makes it call only once you let go
[self.sizeSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
sampleTextString = [[NSMutableAttributedString alloc] initWithString:@"The Quick Brown Fox Jumps Over The Lazy Dog!"];
self.sampleText.attributedText = sampleTextString;
[sampleTextString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:textsize] range:NSMakeRange(0, sampleTextString.length)];
}
-(void)valueChanged:(UISlider *)sender{
NSUInteger index = (NSUInteger)(self.sizeSlider.value + 0.5); // round the slider position to the nearest index of the numbers array
[self.sizeSlider setValue:index animated:NO];
NSNumber *number = numbers[index]; // <-- This numeric value you want
[sampleTextString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:[number floatValue]] range:NSMakeRange(0, sampleTextString.length)];
[defaults setInteger:[number integerValue] forKey:@"fontSize"]; // Saving fontSize to NSUserDefaults
[defaults synchronize];
self.sampleText.attributedText = sampleTextString;
}
@end
答案 0 :(得分:0)
答案来自rmaddy - 谢谢!
我需要查看索引,而不是数组的实际值。
NSInteger indexText = [numbers indexOfObject:[NSNumber numberWithInteger:textsize]];
所以我把它放进去,然后返回了我想要的滑块位置的索引。