iPhoneOS SDK – iPad Design Template – Multiple Views with Group Table View as the Master View Controller

April 21st, 2010 iPhone SDK Tips

Here’s my favorite iPad Project Template. Modified for 6 view controllers, split view, master tableview uses sections, and is in group format!

Screenshot2010-04-14at18.03.13.kPF6RWxDwfm2.jpg

iPhoneOS SDK – Subclassing a UITableview

April 20th, 2010 iPhone SDK Tips

This is more of a personal reminder about how to subclass a UITableViewCell, but this should be useful to the discerning reader. All the edits required to subclass are the lower code line in each section, the above is the default code (commented out).

.m file Modifications

#import “UITableViewCellFixed.h”

// Below is first the original then the subclassed
        //UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
        UITableViewCellFixed *cell = (UITableViewCellFixed *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
if (cell == nil) {
                
// Below is first the original then the subclassed
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
cell = [[[UITableViewCellFixed alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
                
                
//Cell Accessories
                //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
                

}

Then the subclass file looks like:

// UITableViewCellFixed.h
//

#import <UIKit/UIKit.h>

@interface UITableViewCellFixed : UITableViewCell {

}

@end

//
// UITableViewCellFixed.m
//

#import “UITableViewCellFixed.h”

@implementation UITableViewCellFixed
- (
void) layoutSubviews {
        [
super layoutSubviews];
        
self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x,
4.0,
self.textLabel.frame.size.width,
self.textLabel.frame.size.height);
        
self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x,
                                                                                        
8.0 + self.textLabel.frame.size.height,
                                                                                        
self.detailTextLabel.frame.size.width,
                                                                                        
self.detailTextLabel.frame.size.height);
}
@end

iPhoneOS SDK – iPad Popover Controller

April 19th, 2010 iPhone SDK Tips


The iPad Popover control is possibly the least publicized feature of the iPhoneOS SDK, but becomes critical to in app actions and workflows. This is because the Popover Controller can show a small UIView of controls and more importantly save the user from having the whole screen change navigation hierarchy. A simple popover for example, can be used to edit a textfield, or change a date really quickly. In an iPhone app, this would typically be done by sending the user to a ‘DetailView’ where the setting/property can be change, whereas on the iPad this is highly discouraged. I am going to go through a quick popover example today, and on monday I will post a fantastic iPad user template.

1. Understanding the context
First, you need to know where a popover should be used. I can’t say much more than whats above. Use the apple apps, use the other top 100 apps, see how they use the popover controller. This will give you a feel of what it should do.
2. Some Code
Firstly, your main view controller {.h} needs a <UIPopoverControllerDelegate> declaration.
In your main view controller, add the following to the @interface (.h file)

//PopoverViewController
UIPopoverController *popoverController;

and just before @end add an IBAction:
- (IBAction)popOverViewCall:(id)sender;

Create a New View & ViewController {.h/.m} files and place them in your project. This is the actual popover that will come up. Place controls how ever you see fit.  I call this popover controller MyViewControllerForPopover. Add an include of this file to your main view controller, eg:
#import “FirstDetailViewControllerPopOverControl.h”

In MyViewControllerForPopop {.m file}, add the following code:
-(void)viewDidAppear:(BOOL)animated
{
self.contentSizeForViewInPopover = CGSizeMake(320,320);

}
This sets the size of the popover for showing.Go into interface builder and add a couple controls to ensure you know when it works.
And finally in your main view controller {.m file}, add the IBAction:

-(IBAction)popOverViewCall:(id)sender{
FirstDetailViewControllerPopOverControl *myViewControllerForPopover = [[FirstDetailViewControllerPopOverControl alloc] initWithNibName:@”FirstDetailViewControllerPopOverControl” bundle:nil ];
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:myViewControllerForPopover];
self.popoverController = popover;
popoverController.delegate = self;

[popover release];
[myViewControllerForPopover
release];

CGPoint point = {200,200}; // Place to put on screen
CGSize size = {600,600}; // A content range (see apple docs)
[popoverController presentPopoverFromRect:CGRectMake(point.x, point.y, size.width, size.height)
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

}

Add a button on your main view controller to call the IBAction. That covers it! One of the new features in iPhoneOS3.2 for iPad. See the screenshots for how it should look, code is downloadable below.
















iPhone SDK – Get Current Touch Location

April 16th, 2010 iPhone SDK Tips

Quick one today, I’m working on something new. It neeeded the last touch location to display some user input. It took me a little while to figure out how to call the location of the currently touched location, but its simple.

Just paste the following method into a viewcontroller:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        // get touch event
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];
        NSLog(@”Position of touch: %.3f, %.3f”, pos.x, pos.y);
}

thats it! Check the Console/Log to see the output.
Note, using this over a tableviewcontroller is a different story, that is something I am yet to need, or figure out.

Screenshot2010-04-13at21.10.23.HdXB78fAPxSp.jpg

iPhoneOS SDK – Custom UISlider Graphics

April 15th, 2010 iPhone SDK Tips
Today I am showing how to add graphics to a UISlider in an iPhone application.
  1. Create a new view based application

Screenshot2010-04-12at15.16.01.BWLVS6GSBm0y.jpg

2. Add the IBOutlets for the UISliders

In the .h file add:

@interface deCustomSliderViewController : UIViewController {

IBOutlet UISlider *slider1;
IBOutlet UISlider *slider2;

}

3. Setup the Interface.

Add a couple sliders to deCustomSliderViewController.xib

Screenshot2010-04-12at15.16.28.sp1lJ5YWNXvi.jpg

And then add the IBOutlet Link – You will only need to do one of these.

Screenshot2010-04-12at15.21.24.3QsjTLPg20UI.jpg


4.Now its time to make them pretty!

Add your image resources to the project resources folder. You will need one for the bar and one for the knob (the slider bit you touch). I have attached some at the end of this post.

I am using these (credit http://www.mynameise.com/renn and http://365psd.com/day/27/) :

slider-bg.dc4VNOeb5oj2.jpg
slider-knob.Q7fZFMmAxbX4.jpg

5. Add the UI Code

The final step is just linking the resources to the IBOutlets. Add the following code in your viewDidLoad or viewWillLoad

//Slider Images
UIImage *stetchLeftTrack = [[UIImage imageNamed:@"slider-bg.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
UIImage *stetchRightTrack = [[UIImage imageNamed:@"slider-bg.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];

//Slider: Top
slider1.backgroundColor = [UIColor clearColor];        
[slider1 setThumbImage: [UIImage imageNamed:@"slider-knob.png"] forState:UIControlStateNormal];
[slider1 setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[slider1 setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
slider1.minimumValue = 0.0;
slider1.maximumValue = 100.0;
slider1.continuous = YES;
slider1.value = 20.0;

//Slider: Middle
slider2.backgroundColor = [UIColor clearColor];        
[slider2 setThumbImage: [UIImage imageNamed:@"slider-knob.png"] forState:UIControlStateNormal];
[slider2 setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[slider2 setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
slider2.minimumValue = 0.0;
slider2.maximumValue = 100.0;
slider2.continuous = YES;
slider2.value = 50.0;

Thats it! It wasn’t too hard at all hey! Run your app and checkout your new sliders. Mine Looks like this:

Screenshot2010-04-12at15.32.32.VwGIIsHQSwar.jpg


And thats it!

Downloads:

IPhone OS SDK – Use a Zombie to get a better errors about memory allocation

April 14th, 2010 iPhone SDK Tips

Just a quick note, theres lots of information about NSZombie (NSZombieEnabled), heres the way to enable them:

1. Project -> Edit Active Executable
Screenshot2010-04-11at13.46.39.Qrxcr6fUafop.jpg

2. Goto the Arguments Tab
Screenshot2010-04-11at13.50.31.LmqbaOs3Zmrh.jpg

Screenshot2010-04-11at13.50.34.zbnOfZ81E3Ob.jpg

  1. Set the Variable NSZombieEnabled and set it to YES (note: its Zombie, not Zombies!)

I’ll leave it as an exercise to find out more about NSZombie, its great for memory debugging.

iPhone SDK – Animate button press (highlight) with alternate buttons

April 13th, 2010 iPhone SDK Tips

I was interested in implementing a simple button, which had a normal state and a ‘pressed’ or ‘highlighted’ state when being touched. I found an endless supply of lines of code, but after a little more playing around I found something new. And, it uses my fantastic principle of ‘simple’!

Firstly, what does the button look like? Its very simple really, its a modest edit button. The left image is the Normal state, the right button is for the highlighted state.

button-edit.aRIFeugod4Dy.jpgbutton-edit-toucheddown.j8VuddV07gAQ.jpg

And here is a (blurred) pic of the edit button in action, in my current development app. I did say it is modest.

Screen-shot-2010-04-07-at-23.31.28.ZpA61gVboFc3.jpg

So how is it done?

Well this one is 100% thanks to Interface Builder and it should be quite easy to follow.

Well, open Interface Builder, create a UIButton and add an Image to the button (as one normally would). See the below screenshot.
Screenshot2010-04-07at23.31.45.7ZbhOvcKdeMV.jpg

Now, Do you see where it says ‘Default State Configuration’ just under the ‘type’ setting? Press it

Screenshot2010-04-07at23.31.54.wVlfeQWuTcPN.jpg
We are now given 4 states where we are able to alter the button under, all without requiring any code at all!
Default State: Button is in its normal state
Highlighted State: Button is being pressed (this is the one we want)
Selected State: Extra code has registered this button as ‘active’ and so its in ‘selected’ mode
Disabled State: Extra code has registered this button as ‘disabled’ and so its in ‘disabled’ mode

So now I would go into ‘Highlighted State’ and just change the image, to the second edit image (see below).

Screenshot2010-04-07at23.31.56.WW7EQZ1udtpy.jpg

And thats it! No code at all. Build your app and test it!

Future Exercise:
Create the entire button without even the jpgs (Skill: Beginner)



Download: PSD Files (free for personal/commercial use)

iPhone OS SDK – Single time showing popup for users

April 12th, 2010 iPhone SDK Tips

It may sometimes be useful to show a one time reminder to your user in your application. This might be asking for a iTunes review, additions to social networks or any other task that It may be rude to ask more than once.

That is exactly what I have put into my application SavingsGoal, with a single time popup in the about screen. This is shown in detail in the example below:

First in viewDidLoad(), I have a reference to the firstViewSocialPopup class.

- (void)viewDidLoad {
[
super viewDidLoad];
        
        
//Internet Links
        websiteURL = @“http://apps.duivesteyn.net;
        
supportEmail = @“apps@duivesteyn.net;
        
facebookURL = @“http://www.facebook.com/apps/application.php?id=107880612574963;
        
twitterURL = @“de_applications”;
        
        [
self firstViewSocialPopup];
}

in my .h header file, I have of course added:

-(void)firstViewSocialPopup;

Back in the .m file class I have the method firstViewSocialPopup, which is just checking a NSUserDefaults setting and displaying a UIAlert.

-(void)firstViewSocialPopup{
        NSString *socialPopup = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@”toggle_social”]];
        NSLog(@”Social Reminder Status: %@”,socialPopup);
        
        if ([socialPopup isEqualToString: @"YES"]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Social Networking” message:@”Would you help the development team by adding them on Social Networks?” delegate:self cancelButtonTitle:@”No Thanks” otherButtonTitles:@”Twitter”,@”Facebook”,nil];
                [alert show];
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:@"NO" forKey:@"toggle_social"];
        }
        
}

THe UIAlert has delegate self and so sends the button pressed to the UIAlertView delegate (which is its self). This will call the class: (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex

And so, in the same class (.m file) I have the following method:

- (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
        NSLog(@“in alertView action, buttonIndex: %u”,buttonIndex);
        
        if (buttonIndex==1) {
                NSLog(@“Open Twitter”);

                //Custom Open Twitter Page Code
                deHelpers *dehelper = [[deHelpers alloc] init];
                [dehelper openTwitterAppForFollowingUser:@“de_applications"];
                
        } else if (buttonIndex==2) {
                NSLog(@“Open Facebook”);
                
                //Custom Open Twitter Page Code
                url = [NSURL URLWithString:@“http://www.facebook.com/apps/application.php?id=107880612574963"];
                
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                PWWebViewController *webController = [[PWWebViewController alloc] initWithRequest:request];
                
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:webController];
                UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                                                                                                         target:self
                                                                                                                                                                         action:@selector(dismissModal)];
                webController.navigationItem.leftBarButtonItem = cancelButton;
                [cancelButton release];
                [self presentModalViewController:navigationController animated:YES];
                [navigationController release];
                
        }
        
}

Hopefully, you can see the idea, its quite simple. I have included some extra parts in the code for those who are interested exactly how I implement the popup actions. Its using a previously discussed control: PWWebViewController and some DrTouch code: openTwitterAppForFollowingUser.


social.hRbsv9NjXBdY.jpg

See some of the new stuff in iPhone 4.0

April 9th, 2010 iPhone SDK Tips

The link is here: http://events.apple.com.edgesuite.net/1004fk8d5gt/event/

iPhone OS SDK – Insert a random Number

April 9th, 2010 iPhone SDK Tips

Generating a random number is a simple task in Objective-C.

all you really need to do is:
int random = random();

Then you can use the integer as you normally would.

But wait..is it possible that I keep getting the same random numbers?

Try the following code in an empty Xcode Project:

int generated;

for (int i =0; i<10; i++) {
generated = abs(100000*(random()));
NSLog(@”New Random Key: %d”,generated);
}

This gives the output of:
Screenshot2010-04-02at14.14.58.j18TEMlrVoXN.jpg
And yes, they are the same 10 randomly generated numbers! The random number sequence by default is regular and is based off local computer properties. (Note: see how I ran the code twice and I get the same 10 random numbers).

There is one more line that can aid the initial random() function, and makes the start a little less random.

//Real Randomness
srandom(time(NULL));

Put this before the use of random().

This now sets a new starting point for the random number generator and gives output like one would expect.

//Real Randomness
srandom(time(NULL));

int generated;

for (int i =0; i<10; i++) {
generated = abs(100000*(random()));
NSLog(@”New Random Key: %d”,generated);
}

This gives the output: Screenshot2010-04-02at14.15.38.KqQYLXoKVjJM.jpg

There is one better function to use in place of all of the above. Just use

arc4random()

It seems to be more popular and improves generation with unique-randoms. I use arc4random and this is the best way to quickly generate a random number in Objective-C.