Great UIKit/Objective-C code snippets

2019-01-29 15:03发布

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.

5条回答
别忘想泡老子
2楼-- · 2019-01-29 15:25

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];
查看更多
祖国的老花朵
3楼-- · 2019-01-29 15:32
  1. Display an alert window:

    UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"too many alerts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show] 
    
  2. Get the path to the Documents folder:

    NSArray*  paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString* documentsDirectory = [paths objectAtIndex:0];
    
  3. Push another view controller onto the Navigation Bar:

    [self.navigationController pushViewController:anotherVC animated:YES];
    
  4. 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];                      
    
  5. Get the name of the app

    self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    
  6. Change the status bar to black

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    
  7. Change the style of the navigation bar (from in a view controller):

    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
  8. Save a NSString into NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:loginName forKey:kUserLoginName];
    
  9. Get an NSString from NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    

    NSString* loginName = [defaults stringForKey:kUserLoginName];

  10. Check to make sure an objects support a method before calling it:

    if ([item respondsToSelector:@selector(activateBOP:)]) {
        [item activateBOP:closeBOP];
    }
    
  11. Log the name of the class and function:

    NSLog(@"%s", __PRETTY_FUNCTION__);
    
  12. 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
    
  13. 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]]; 
    
查看更多
家丑人穷心不美
4楼-- · 2019-01-29 15:36

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;
查看更多
Explosion°爆炸
5楼-- · 2019-01-29 15:40

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]]]];
查看更多
虎瘦雄心在
6楼-- · 2019-01-29 15:48

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);
查看更多
登录 后发表回答