This is a sample source code (no interface builder file) implementing the one similar to Setting Bundle for UIKit Controls
UISlider, UITextField, UISwitch & UISegmentedControl
- main.m Select all
// main.m
// Settings
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
[pool release];
return retVal;
}
- AppDelegate.h Select all
// AppDelegate.h
// Settings
//
#import <UIKit/UIKit.h>
#pragma mark -
#pragma mark MainViewController
#pragma mark -
@interface MainViewController : UITableViewController <UITextFieldDelegate>{
UITextField *activeTextField;
}
- (id) init;
- (void) dealloc;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
@end
#pragma mark -
#pragma mark AppDelegate
#pragma mark -
@interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
MainViewController *viewController;
UINavigationController *navigationController;
}
@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) MainViewController *viewController;
@end
- AppDelegate.m Select all
// AppDelegate.m
// Settings
//
//
#define DEBUG_BUILD
#ifdef DEBUG_BUILD
#define DEBUGLOG(x) x
#define LogMethod() NSLog(@"%@ %@", self, NSStringFromSelector(_cmd))
#else
#define DEBUGLOG(x)
#define LogMethod()
#endif
#import "AppDelegate.h"
#pragma mark -
#pragma mark MainViewController
#pragma mark -
@implementation MainViewController
- (id) init {
self = [ super initWithStyle: UITableViewStyleGrouped ];
if (self != nil) {
self.title = @"Settings";
}
return self;
}
- (void) loadView {
LogMethod();
[ super loadView ];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
LogMethod();
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
LogMethod();
[ super didReceiveMemoryWarning ];
}
- (void)dealloc {
// [ shipStabilityControl release ];
[ super dealloc ];
}
#pragma mark - UITableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
case(0):
return 4;
break;
case(1):
return 3;
break;
case(2):
return 1;
break;
}
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
switch (section) {
case(0):
return @"Game Settings";
break;
case(1):
return @"Advanced Settings";
break;
case(2):
return @"About";
break;
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [ NSString stringWithFormat: @"%d:%d", [ indexPath indexAtPosition: 0 ], [ indexPath indexAtPosition:1 ]];
UITableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
cell = [ [ [ UITableViewCell alloc ] initWithFrame: CGRectZero reuseIdentifier: CellIdentifier] autorelease ];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
switch ([ indexPath indexAtPosition: 0]) {
case(0):
switch([ indexPath indexAtPosition: 1]) {
case(0):
{
UISlider *musicVolumeControl = [ [ UISlider alloc ] initWithFrame: CGRectMake(170, 0, 125, 50) ];
musicVolumeControl.minimumValue = 0.0;
musicVolumeControl.maximumValue = 10.0;
musicVolumeControl.tag = 0;
musicVolumeControl.value = 3.5;
musicVolumeControl.continuous = YES;
[musicVolumeControl addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[ cell addSubview: musicVolumeControl ];
cell.textLabel.text = @"Music Volume"; // OS3
// cell.text = @"Music Volume";
[ musicVolumeControl release ];
}
break;
case(1):
{
UISlider *gameVolumeControl = [ [ UISlider alloc ] initWithFrame: CGRectMake(170, 0, 125, 50) ];
gameVolumeControl.minimumValue = 0.0;
gameVolumeControl.maximumValue = 10.0;
gameVolumeControl.tag = 1;
gameVolumeControl.value = 3.5;
gameVolumeControl.continuous = YES;
[gameVolumeControl addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[ cell addSubview: gameVolumeControl ];
cell.textLabel.text = @"Game Volume"; // OS3
// cell.text = @"Game Volume";
[ gameVolumeControl release ];
}
break;
case(2):
{
UISegmentedControl *difficultyControl = [ [ UISegmentedControl alloc ] initWithFrame: CGRectMake(170, 5, 125, 35) ];
[ difficultyControl insertSegmentWithTitle: @"Easy" atIndex: 0 animated: NO ];
[ difficultyControl insertSegmentWithTitle: @"Hard" atIndex: 1 animated: NO ];
difficultyControl.selectedSegmentIndex = 0;
difficultyControl.tag = 2;
[difficultyControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
[ cell addSubview: difficultyControl ];
cell.textLabel.text = @"Difficulty"; // OS3
// cell.text = @"Difficulty";
[difficultyControl release];
}
break;
case(3):
{
UISegmentedControl *actionControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects: @"Check", @"Search", @"Tools", nil]];
actionControl.frame = CGRectMake(145, 5, 150, 35);
actionControl.selectedSegmentIndex = 1;
actionControl.tag = 3;
[actionControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
actionControl.segmentedControlStyle = UISegmentedControlStyleBar;
[cell addSubview:actionControl];
cell.textLabel.text = @"Actions"; // OS3
// cell.text = @"Actions";
[actionControl release];
}
break;
}
break;
case(1):
switch ([ indexPath indexAtPosition: 1 ]) {
case(0):
{
UITextField *playerTextField = [ [ UITextField alloc ] initWithFrame: CGRectMake(150, 10, 145, 34) ];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.font = [UIFont systemFontOfSize:17.0];
playerTextField.placeholder = @"";
playerTextField.backgroundColor = [UIColor clearColor];
playerTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
playerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
playerTextField.textAlignment = UITextAlignmentRight;
playerTextField.keyboardType = UIKeyboardTypeDefault; // use the default type input method (entire keyboard)
playerTextField.returnKeyType = UIReturnKeyDone;
playerTextField.tag = 0;
playerTextField.delegate = self;
playerTextField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
playerTextField.text = @"";
[ playerTextField setEnabled: YES ];
[ cell addSubview: playerTextField ];
cell.textLabel.text = @"Player"; // OS3
// cell.text = @"Player";
[playerTextField release];
}
break;
case(1):
{
UISwitch *resetControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
resetControl.on = YES;
resetControl.tag = 1;
[resetControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
[ cell addSubview: resetControl ];
cell.textLabel.text = @"Reset"; // OS3
// cell.text = @"Reset";
[resetControl release];
}
break;
case(2):
{
UISwitch *debugControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
debugControl.on = NO;
debugControl.tag = 2;
[debugControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
[ cell addSubview: debugControl ];
cell.textLabel.text = @"Debug"; // OS3
// cell.text = @"Debug";
[debugControl release];
}
break;
}
break;
case(2):
{
UITextField *versionControl = [ [ UITextField alloc ] initWithFrame: CGRectMake(170, 10, 125, 38) ];
versionControl.text = @"1.0.0 Rev. B";
[ cell addSubview: versionControl ];
[ versionControl setEnabled: YES ];
versionControl.tag = 2;
versionControl.delegate = self;
cell.textLabel.text = @"Version"; // OS3
// cell.text = @"Version";
[versionControl release];
}
break;
}
}
return cell;
}
#pragma mark ControlEventTarget Actions
- (void)segmentAction:(UISegmentedControl*)sender
{
if ([activeTextField canResignFirstResponder])
[activeTextField resignFirstResponder];
DEBUGLOG(NSLog(@"segmentAction: sender = %d, segment = %d", [sender tag], [sender selectedSegmentIndex]));
}
- (void)sliderAction:(UISlider*)sender
{
if ([activeTextField canResignFirstResponder])
[activeTextField resignFirstResponder];
DEBUGLOG(NSLog(@"sliderAction: sender = %d, value = %.1f", [sender tag], [sender value]));
}
- (void)switchAction:(UISwitch*)sender
{
if ([activeTextField canResignFirstResponder])
[activeTextField resignFirstResponder];
DEBUGLOG(NSLog(@"switchAction: sender = %d, isOn %d", [sender tag], [sender isOn]));
}
#pragma mark <UITextFieldDelegate> Methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
activeTextField = textField;
DEBUGLOG(NSLog(@"textFieldShouldBeginEditing: sender = %d, %@", [textField tag], [textField text]));
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
DEBUGLOG(NSLog(@"textFieldDidEndEditing: sender = %d, %@", [textField tag], [textField text]));
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
DEBUGLOG(NSLog(@"textFieldShouldReturn: sender = %d, %@", [textField tag], [textField text]));
activeTextField = nil;
[textField resignFirstResponder];
return YES;
}
@end
#pragma mark -
#pragma mark AppDelegate
#pragma mark -
@implementation AppDelegate
@synthesize window;
@synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
LogMethod();
// If you want the status bar to be hidden at launch use this:
// application.statusBarHidden = YES;
//
// To set the status bar as black, use the following:
// application.statusBarStyle = UIStatusBarStyleBlackOpaque;
// Create window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// this helps in debugging, so that you know "exactly" where your views are placed;
// if you see "red", you are looking at the bare window, otherwise use black
// window.backgroundColor = [UIColor redColor];
viewController = [ [ MainViewController alloc ] init ];
navigationController = [ [ UINavigationController alloc ] initWithRootViewController: viewController ];
/* Anchor the view to the window */
[window addSubview:[navigationController view]];
/* Make the window key and visible */
[window makeKeyAndVisible];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
// low on memory: do whatever you can to reduce your memory foot print here
}
- (void)dealloc
{
[viewController release];
[navigationController release];
[window release];
[super dealloc];
}
@end
11 comments:
Very useful post. Works great thanks.
i thought table cells, not being a view, could not contain subviews .... is this particular to the UIKit UITableViewCell ??
Such blog posts are much more helpful then official documentation by Apple :P Thank you.
Few days ago I wrote a tutorial with sample code about UISlider ... if anyone's interested: http://www.xprogress.com/post-36-threading-tutorial-using-nsthread-in-iphone-sdk-objective-c/
Cheers,
Ondrej
nice post, good help, exactly what I was looking for AND some more
need some update for 3.1. Obviously, it doesn't work. Any idea?
Any ideas why the keyboard wont go away if I tap on the table view outside a row? I tried putting a button under the table but it doesn't detect scrolling or touching a section title for instance.
thanks,
ward
Very handy, thank you.
What did I do wrong?
Everything looks/works fine... until I scroll far up or down... then the objects start appear OVER each other.
Help!
Most useful dude. Thank you.
This is what I am looking for... Can you post the code of this example please!
Post a Comment