Cocoa-Matic

iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Friday, August 20, 2010

Create UIPickerView programmatically

The UIPickerView is one of the input controls in iOS for displaying and selecting a list of data. Most tutorials implement this control in Interface Builder, which is fine, but I like to have more control and do most everything in code. There are several components to doing this 100% programmatically, which I will demonstrate below...

The first thing we have to do is include the UIPickerViewDelegate in the interface of our class .h file.
@interface myViewController : UIViewController<UIPickerViewDelegate>
Read more »

Labels: , ,

Wednesday, August 18, 2010

Prevent UITableView from scrolling

Quick tip:

UITableView elements enable vertical scrolling by default. The following code disables the scroll:
myTableView.scrollEnabled = NO;

Labels: , , ,

Tuesday, August 17, 2010

Random Number in Cocoa and Objective-c

Generating a random number is fairly simple using arc4random(). Say you want a random integer between 10 (min) and 1000 (max). Here's how to do it:

int max = 1000;
int min = 10;
int value = (arc4random() % max) + min;

Also, no need to do any seeding with this method.

Labels: ,

Friday, August 13, 2010

Unwanted UITableView gray background on iPad

I came across something weird when developing an iPad app. I have a UITableView that does not encompass the entire screen and I have it set to grouping mode so it has nice looking rounded corners. For some reason when this is displayed, the background of the UITableView is light gray. It seems to be ignoring the backgroundColor property.

So, here's the fix:
Read more »

Labels: , , ,

Asynchronous data request class

A very handly class I've built is asyncDataRequest. This provides for an easy way to make and receive calls to web data feeds. All you have to do is include the class reference in your .m file, make the request and create a notification responder to receive and parse that data response.

First, we'll look at asyncDataRequest.h:
@interface asyncDataRequest : NSObject {
 NSMutableData *responseData;
 id delegate;
 NSString *notificationName;
}

@property(nonatomic,retain) NSMutableData *responseData;
@property(nonatomic,assign) id delegate;
@property(nonatomic,retain) NSString *notificationName;

- (void)setDelegate:(id)newDelegate;
- (void)connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error;
- (void)connectionDidFinishLoading: (NSURLConnection *)connection;

@end

Read more »

Labels: , , , ,

Thursday, August 12, 2010

UIButton with custom UIImage

Most developers want to steer clear of the default buttons provided in Cocoa because they're just not that attractive. The following code shows how to programmatically create an image button and define an action for when the button is pressed.
// Create button and set frame
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
// Set button image, in this case "my_image.png"
[myButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my_image" ofType:@"png"]] forState:UIControlStateNormal];
// Call buttonWasPressed function when button is touched
[myButton addTarget:self action:@selector(buttonWasPressed) forControlEvents:UIControlEventTouchUpInside];
// Add the button to view
[self.view addSubview:myButton];

Labels: , ,

Thursday, August 5, 2010

UILabel dynamic sizing based on string

Here's how to create a UILabel that dynamically resizes to fit the NSString that is loaded into it:
UILabel *tmpTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
self.titleLabel = tmpTitleLabel;
[tmpTitleLabel release];
self.titleLabel.textColor = [UIColor blackColor];
self.titleLabel.font = [UIFont boldSystemFontOfSize:16];
self.titleLabel.numberOfLines = 0;
self.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
self.titleLabel.text = self.myTitleString;
 
//Calculate the expected size based on the font and linebreak mode of label
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [self.myTitleString sizeWithFont:self.titleLabel.font constrainedToSize:maximumLabelSize lineBreakMode:self.titleLabel.lineBreakMode];
 
//Adjust the label the the new height
CGRect newFrame = self.titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
self.titleLabel.frame = newFrame;
And here's the explanation of what's going on with this code:
Read more »

Labels: , , ,

Wednesday, August 4, 2010

Better NSLog implementation

NSLog is an invaluable tool for developers who are looking to debug and/or troubleshoot code. It outputs to the debugger console during the application runtime. Before I show a better way to use the NSLog function, let's go over the basics with an example:

int myInt = 100;
NSLog(@"The value of myInt: %i", myInt);
This will output:
The value of myInt: 100

Depending on what type of value you're trying to print, you'll have to use different Format Specifiers (%i in the previous example). Here's a list of common Format Specifiers:
Read more »

Labels:

Tuesday, August 3, 2010

UITextField: Only allow numeric entry using NSScanner

Have a UITextField and want to prevent the user from entering anything but numbers (and decimal point)? This quick function utilizing the UITextFieldDelegate will do the trick.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

 NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
 
 // This allows backspace
 if ([resultingString length] == 0) {
  return true;
 }

 double holder;
 NSScanner *scan = [NSScanner scannerWithString: resultingString];
 
 return [scan scanDouble: &holder] && [scan isAtEnd];
}
Read more »

Labels: , , ,


« Older Entries  
Newer Entries »