This is the final workshop in the App Preferences Workshop series. You’ll design and code the Basic Prefs tab. It enable the user to view and update preferences you’ve set up in the setting bundle’s Root.plist file, within the application itself.
Start by designing the SecondViewController’s view to look like what’s shown in the image below. The table to the right of the image, shows what controls and attributes to modify.
Next, add code shown below in the SecondViewController files.
SecondViewController.h | SecondViewController.m |
---|---|
#import <UIKit/UIKit.h> @interface SecondViewController : UIViewController @property (nonatomic, retain) IBOutlet UITextField *username; @property (nonatomic, retain) IBOutlet UITextField *password; // This method update the Root.plist file's preferences -(IBAction) saveSettings: (id) sender; -(IBAction) doneEditing: (id) sender; @end |
#import "SecondViewController.h" @implementation SecondViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Set the tab bar's title and image self.title = @"Basic Prefs"; self.tabBarItem.image = [UIImage imageNamed:@"32-iphone"]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Create an object of the NSUserDefaults class NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; // Initialize the Text Fields controls with preferences stored in the Root.plist file self.username.text = [defaults objectForKey:@"kusername"]; self.password.text = [defaults objectForKey:@"kpassword"]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction) saveSettings: (id) sender { // Create an object of the NSUserDefaults class NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; // Set the username and password preferences [defaults setObject:self.username.text forKey:@"kusername"]; [defaults setObject:self.password.text forKey:@"kpassword"]; // Update preferences in the Root.plist file [defaults synchronize]; // Set up and display a success message in an alert view UIAlertView *alert; alert = [[UIAlertView alloc] initWithTitle:@"Update Successful!" message:@"You may terminate the app now." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } // This method dismiss the keyboard when the user tap the view's background - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } @end |
Connect the user interface’s controls in Interface Builder then run the application. These images shows what the SecondViewController nib file’s user interface looks like in the iPhone Simulator.