Thursday, July 29, 2010

Using Next and Done with UITextFields and UIKeyboard

So you've probably seen in interface builder that its quite simple to pick which enter key you will use in your keyboard for a given UITextField. The minor complexity is that these different labels don't mean anything unless you add some code in your controller to handle the actions. Let's say you have three UITextFields:
  1. Username
  2. Password
  3. Email
You would want to set the first two to 'next' and the last to 'done' in interface builder. Then, you will need to implement UITextFieldDelegate in your View Controller, and use the following:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == txtUsername) {
[txtPassword becomeFirstResponder];
}
else if (textField == txtPassword) {
[txtEmail becomeFirstResponder];
}
[textField resignFirstResponder];
return YES;
}

Monday, July 26, 2010

XCode 4 Developer Preview

Well, as registered developers we aren't really allowed to talk about it, but I'll just say WOW it is seriously nice. This is the first huge upgrade to XCode in a long time. It actually doesn't feel like Project Builder any more, and we can use git!

Friday, July 23, 2010

Accessing your UITabBarController from another UIViewController

I recently came across a situation where I wanted to show the user a UIAlertView on a view listing data if there was no data entered yet, and then direct them to an 'Add' tab in my application after they clicked OK. I ended up doing this by accessing my application's delegate which then had access to the Tab Bar Controller of the entire application.

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//only one alertview so we'll just push here
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[[appDelegate tabBarController] setSelectedIndex:1];
}

The indexing is zero-based, as expected, so don't forget that :)

Setting the color of a UINavigationBar programmatically

If you are using a UINavigationController for your views, you can easily change the UINavigationBar's color using the following:

self.navigationController.navigationBar.tintColor = [UIColor brownColor];

and choose whatever color you wish.

Wednesday, July 21, 2010

Converting NSString to int, float, double, and bool

Here's another really basic & simple NSString tip for today to help you convert strings to various basic types. The NSString class has a bunch of conversions already built in:

float stringFloat = [myString floatValue];
int stringInt = [myString intValue]
double stringDouble = [myString doubleValue]
BOOL boolValue = [myString boolValue];

Easy NSString substring

Sadly, creating a simple substring in Objective-C isn't quite as obvious as in other languages. Here's a basic method to grab a substring of a given string before a defined character, in my case the ":" character:

NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(0, end.location)]];

If you wanted grab a string between two characters, you could do:

NSRange start = [_contentsOfElement rangeOfString:@"|"];
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(start.location, end.location)]];

Monday, July 19, 2010

UITextView automatic keyboard display

I've come across a few instances where my view is simply a UITextView for the user to enter some text into, such as for a comment field, or a twitter entry, etc. In these scenarios it is best to automatically show the UIKeyboard for the user to just start typing. This is a really easy one, all you have to do is have the synchronized UITextView become the first responder to make the keyboard appear:

- (void)viewDidLoad {
    [super viewDidLoad];
    [commentTxt becomeFirstResponder];
}

You can use the same technique with UITextFields too.

Friday, July 16, 2010

Deselecting UITableViewCell's when a view appears

Here's a simple tip to make your application look a little more polished. It's very common for us to push new view controllers when a row is selected in a UITableView. If the user uses a UINavigationBar button to go back to the previous view, or the new view controller gets popped in some other manner, you will want to remove the highlight from the selected UITableViewCell. Here's a simple snippet to add to do just that assuming you have a UITableView that is an IBOutlet on your view controller:

- (void) viewDidAppear:(BOOL)animated {
if ([self.table indexPathForSelectedRow]) {
[self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:YES];
}
}

Facebook API Integration on the iPhone

This is another short post, for I can't take credit for any of the code. I just wanted to pass across a link to the Facebook iPhone SDK that they've put together. I despise Facebook, but must admit this is one of the most well polished and documented libraries for the iPhone that I've seen yet. The framed webview that pops up for the authorization looks great.

Thursday, July 8, 2010

Default UITableViewCell font, and how to change it

The default font is... Helvetica! If you want to change the size of the font, you can use:

cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0];

You can also change the font using the above statement with a different font name.

Hiding the keyboard when using UISearchBar and UITableView

In one of my recent applications, I set up a UIViewController containing a UISearchBar and a UITableView. I implemented all the necessary delegate methods for both classes, and my search was working just fine (after working out a few kinks..). I did have one remaining problem though... Since I was searching as the user was typing, similar to an autocomplete on the web, the results were automatically being shown in the tableview but the keyboard was still there! This only showed the user a few results and was not very user friendly. I next figured out how to hide the keyboard once the user touched the tableview and started scrolling.

It's actually really easy to do this - all you have to do is implement the UIScrollViewDelegate as follows:

@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

...and then put the following into your class.m source:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[search resignFirstResponder];
}

HTTP Basic Authentication on the iPhone

I can't steal credit for this one. I just wanted to pass along this excellent link to a post titled Objective-C and HTTP  Basic Authentication. It still amazes me that the iPhone SDK doesn't have base 64 encoding built in... but at least some smart folks out there have gone through the trouble of putting it together for us.

What I ended up doing was putting the encode function in my parent REST client class, then I was able to call it as necessary in my subclasses.

NSURLErrorDomain error -1012

So have you run across this one when trying to issue some url requests? What it means is there was an authentication error - NSURLErrorUserCancelledAuthentication. Okay, so what does that mean? You likely are trying to issue a synchronous http request and not passing proper authentication, or you've messed up your auth in some other manner. It's a lot easier to handle authentication when using asynchronous calls and responding to the auth challenge:

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:@"username"
                                                 password:@"password"
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

Changing UITableViewCell text colors

This is a really easy but, but may not be immediately apparent. Personally, I first tried changing the color of the cell directly, then tried changing the color of the text within the cells. What you actually need to do is change the textColor property of the UILabel's that are inside of the cell. For example, if you want to change the color of the textLabel, you would use:

cell.textLabel.textColor = [UIColor lightGrayColor];

The same goes for the detail label if you are using that type of cell:

cell.detailTextLabel.textColor = [UIColor blackColor];