Skip to main content

Great UIKit/Objective-C code snippets



New to Objective-C iPhone/iPod touch/iPad development, but I'm starting to discover lots of power in one-liners of code such as this:







[UIApplication sharedApplication].applicationIconBadgeNumber = 10;







Which will display that distinctive red notification badge on your app iphone with the number 10.





Please share you favorite one or two-liners in Objective-C for the iPhone/iPod touch/iPad here. PUBLIC APIs ONLY .


Comments

  1. Open an URL in Safari

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]];


    Hide the status bar

    [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];


    Dial a Phone Number (iPhone Only)

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://9662256888"]];


    Launch the Apple Mail

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://mymail@myserver.com"]];


    stop responding to touch events

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];


    active the touch events

    [[UIApplication sharedApplication] endIgnoringInteractionEvents];


    Show the network Activity Indicator

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


    Hide the network Activity Indicator

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;


    Prevents iPhone goes into sleep mode

    [UIApplication sharedApplication].idleTimerDisabled = YES;

    ReplyDelete
  2. Display an alert window:

    UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"too many alerts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show]

    Get the path to the Documents folder:

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];

    Push another view controller onto the Navigation Bar:

    [self.navigationController pushViewController:anotherVC animated:YES];

    Fade away a UIView by animating the alpha down to 0:

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1]; // fade away over 1 seconds
    [aView setAlpha:0];
    [UIView commitAnimations];

    Get the name of the app

    self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];

    Change the status bar to black

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    Change the style of the navigation bar (from in a view controller):

    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

    Save a NSString into NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:loginName forKey:kUserLoginName];

    Get an NSString from NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];


    NSString* loginName = [defaults stringForKey:kUserLoginName];
    Check to make sure an objects support a method before calling it:

    if ([item respondsToSelector:@selector(activateBOP:)]) {
    [item activateBOP:closeBOP];
    }

    Log the name of the class and function:

    NSLog(@"%s", __PRETTY_FUNCTION__);

    Add rounded corners and/or a border around any UIView item (self)

    self.layer.borderColor = [UIColor whiteColor].
    self.layer.cornerRadius = 8; // rounded corners
    self.layer.masksToBounds = YES; // prevent drawing outside border

    Open Google Maps app with directions between two lat/long points

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirflg=d", start.latitude, start.longitude, finish.latitude, finish.longitude];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

    ReplyDelete
  3. Save bool to User Defaults

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Yes Bool"];


    Copy a file from x to y

    [[NSFileManager defaultManager] copyItemAtPath:x toPath:y error:nil];


    Display a new view

    [self presentModalViewController:(UIViewController *) animated:YES];


    Screen touches method

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {}


    Get documents directory

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];


    Load URL

    [MyWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://couleeapps.hostei.com"]]];


    Get Current Date and time:

    NSCalendar *gregorian = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];


    Own enum type:

    typedef enum {
    a = 0, b = 1, c = 2
    } enumName;


    Quartz draw arc

    CGContextRef ctxt = UIGraphicsGetCurrentContext();
    CGContextAddArc(ctxt, x, y, radius, startDeg, endDeg);

    ReplyDelete
  4. Make the device vibrate:

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);


    Open the Messages app with a specific phone number:

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:123456789"]];


    Stop responding to touch events:

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];


    Start responding again:

    [[UIApplication sharedApplication] endIgnoringInteractionEvents];


    And finally, the single line of code browser:

    [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: [urlText stringValue]]]];

    ReplyDelete
  5. Change the title on the back button on a UINavigationView. Use this code on the UINavigationController before pushing the view

    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:nil action:nil];


    self.navigationItem.backBarButtonItem = backBarButtonItem;
    [backBarButtonItem release];

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.