Useful Code Snippet for iOS development

收集整理了一些有用的Snippet Code,在这里整理一下,留着备用。

1. 将一个视图(或者layer)通过设置mask的方法形成圆角效果
QuartzCore.framework is required

// This is much simpler but less control
// four corners will be all set at a time[Yufei Lang <#Time#>]
<#Your View#>.layer.cornerRadius = 8.0;
<#Your View#>.clipsToBounds = YES;
// this will give you more control
// Create the path (with all four corner rounded with radius rate of 8.0f) [Yufei Lang <#Time#>]
UIBezierPath *maskPathCornerRounded = [UIBezierPath bezierPathWithRoundedRect:<#Your View Here#>.bounds byRoundingCorners:
                                       UIRectCornerTopLeft | 
                                       UIRectCornerTopRight | 
                                       UIRectCornerBottomLeft | 
                                       UIRectCornerBottomRight cornerRadii:CGSizeMake(8.0, 8.0)];

// Create the shape layer and set its path [Yufei Lang <#Time#>]
CAShapeLayer *maskLayerCornerRounded = [CAShapeLayer layer];
maskLayerCornerRounded.frame = <#Your View Here#>.bounds;
maskLayerCornerRounded.path = maskPathCornerRounded.CGPath;

// Apply the mask to the view/layer [Yufei Lang <#Time#>]
<#Your View Here#>.layer.mask = maskLayerCornerRounded;

2. 让一个view有地震的效果

// use these methods to control when to start&end [Yufei Lang <#Time#>]
- (void)startWiggle:(UIView *)theView
{
	CALayer *viewLayer = [theView layer];
	CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"animationwiggle"];
	anim.duration = 0.1;
	anim.repeatCount = FLT_MAX;
	anim.autoreverses = YES;
	anim.fromValue = [NSValue valueWithCATransform3D:CATransform3DRotate(viewLayer.transform, -0.1,0.0,0.0,0.5)];
	anim.toValue = [NSValue valueWithCATransform3D:CATransform3DRotate(viewLayer.transform, 0.1,0.0,0.0,0.5)];
	[viewLayer addAnimation:anim forKey:@"wiggle"];
}

- (void)stopWiggle:(UIView *)theView
{
	CALayer *viewLayer = [theView layer];
	[viewLayer removeAnimationForKey:@"wiggle"];
}

3. 制作一个动画块

[UIView beginAnimations:<#Animation Name#> context:NULL];
[UIView setAnimationDuration:<#Animation Time in sec#>];
<#Animation Detail#>
[UIView commitAnimations];

4. 生成一个可以翻页的(paging enabled)scrollView

// set up scroll view [Yufei Lang <#Time#>]
// enable paging [Yufei Lang <#Time#>]
<#YourScrollView#>.pagingEnabled = YES; 
// set scroll indicator [Yufei Lang <#Time#>]
<#YourScrollView#>.showsHorizontalScrollIndicator = NO; 
<#YourScrollView#>.showsVerticalScrollIndicator = NO;
// set delegate to self in order to respond scroll actions [Yufei Lang <#Time#>]
[<#YourScrollView#> setDelegate:self]; 
// you have to set content size if you know or
// you have to set it within the loadPage:toScrollView:ForDirection method by ur self **
<#YourScrollView#>.contentSize = CGSizeMake(<#CGFloat width#>, <#CGFloat height#>);

//-----------------------load page method starts--------------------------
typedef enum
{
    Horizontally    =0,
    Vertically      =1,
}ScrollViewDirection;

- (void)loadPage: (UIView *)viewPage toScrollView: (UIScrollView *) scrollView ForDirection: (ScrollViewDirection) direction
{
    switch (direction) 
    {
        case Horizontally:
        {
            CGFloat newFrameWidth = 0.0f;
            for (UIView * view in scrollView.subviews) {
                newFrameWidth += view.bounds.size.width;
            }
            viewPage.frame = CGRectMake(newFrameWidth, 0, viewPage.bounds.size.width, viewPage.bounds.size.height);
        }
            break;
        case Vertically:
        {
            CGFloat newFrameHeight = 0.0f;
            for (UIView * view in scrollView.subviews) {
                newFrameHeight += view.bounds.size.height;
            }
            viewPage.frame = CGRectMake(0, newFrameHeight, viewPage.bounds.size.width, viewPage.bounds.size.height);
        }
            break; 
        default:
            return;
    }
    [scrollView addSubview:viewPage];
}
//-----------------------load page method ends--------------------------

5. 生成一个警告对话框

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:<#(NSString *)#> message:<#(NSString *)#> delegate:<#(id)#> cancelButtonTitle:<#(NSString *)#> otherButtonTitles:<#(NSString *), ...#>, nil];
[alert show]
[slert release];

6. 生成一个NSURLConnection来访问一个URL

//--------------------------------------------------
// this is a url for testing
//    NSURL *url = [NSURL URLWithString:@"http://phobos.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=75/xml"];

NSMutableURLRequest *req=[[NSMutableURLRequest alloc] 
                          initWithURL:[NSURL URLWithString:<#YourURLString#>] 
                          cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
                          timeoutInterval:5.0];
[req setHTTPMethod: @"GET"]; // set method [Yufei Lang <#Time#>]
/*
 * if the HTTP method is a POST method
 */
// NSString *strPostMessage = [NSString stringWithFormat:<#(NSString *), ...#>];
// [req setHTTPMethod: @"POST"];
// [req setHTTPBody:[strPostMessage dataUsingEncoding:<#NSStringEncoding#>]];
<#YourNSURLConnectionObj#> = [[NSURLConnection alloc] initWithRequest:req delegate:self];

//-----------------------connection delegate starts--------------------------
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
#warning used for debugging, deleate it when release
    // this can let you exam the header file for debugging.
    NSLog(@"Header fields: %@", [(NSHTTPURLResponse*)response allHeaderFields]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [<#YourNSMutableData#> appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [<#YourNSMutableData#> release];
    <#YourNSMutableData#> = [[NSMutableData alloc] init];
#warning used for debugging, deleate it when release or show it to user in a appropriate way
    // this can let you exam the error when request a connection
    NSLog(@"There is an error when request a connection: %@", error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
    // covert the downloaded data to a string if needed
    //NSString *strData = [[NSString alloc] initWithData:<#YourNSMutableData#> encoding:<#NSStringEncoding#>];
    // convert the downloaded data to an image if needed
    //UIImage *imgDownloaded = [UIImage imageWithData:<#YourNSMutableData#>];
    
    // run method here or delegate when download completed. 
    
}
//-----------------------connection delegate ends--------------------------

8. 加速器的简单使用UIAccelerometer (iOS 5.0弃用,盖尔使用Core Motion framework)

UIAccelerometer *theAccel = [UIAccelerometer sharedAccelerometer];
	theAccel.updateInterval = 1.0f / 30.0f; // 更新的时间间隔
	theAccel.delegate = self;

// delegate
- (void) accelerometer:(UIAccelerometer *)accelerometer 
		 didAccelerate:(UIAcceleration *)accel
{
/*
UIAcceleration:
@property(nonatomic,readonly) NSTimeInterval timestamp;
@property(nonatomic,readonly) UIAccelerationValue x;
@property(nonatomic,readonly) UIAccelerationValue y;
@property(nonatomic,readonly) UIAccelerationValue z;
*/
}

9. check the device version (Macros)

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

10. NSDate和NSString互相转换的方法

    NSString * targetString = @"1987-03-16 at 11:30:45";
    
    NSDateFormatter *parseFormat = [[NSDateFormatter alloc] init];
    [parseFormat setDateFormat:@"yyyy-MM-dd 'at' hh:mm:ss"];
    NSDate * date = [parseFormat dateFromString:targetString];
    
    NSDateFormatter * outputFormat = [[NSDateFormatter alloc] init];
    [outputFormat setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
    NSString *outputString = [outputFormat stringFromDate:date];

11.


	

发表评论

电子邮件地址不会被公开。 必填项已用*标注