天天看點

iphone 開發小技巧(持續更新中)

1、如果在程式中想對某張圖檔進行處理的話(得到某張圖檔的一部分)可一用以下代碼:

    1.    UIImage *image = [UIImage imageNamed:filename];  

    2.    CGImageRef imageimageRef = image.CGImage;  

    3.    

    4.    CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);  

    5.    

    6.    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);  

    7.    

    8.    UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

2、判斷裝置是iphone還是iphone4的代碼:

    1.    #define isRetina ([UIScreen instancesRespondToSelector:  

    2.    @selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960),   

    3.    [[UIScreen mainScreen] currentMode].size) : NO)

3、判斷郵箱輸入的是否正确:

    1.    - (BOOL) validateEmail: (NSString *) candidate {  

    2.    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";   

    3.    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];   

    4.    return [emailTest evaluateWithObject:candidate];  

    5.    }

4、如何把目前的視圖作為照片儲存到相冊中去:

    1.    #import <QuartzCore/QuartzCore.h>

    2.    UIGraphicsBeginImageContext(currentView.bounds.size);     //currentView 目前的view  

    3.    [currentView.layer renderInContext:UIGraphicsGetCurrentContext()];  

    4.    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();  

    5.    UIGraphicsEndImageContext();  

    6.    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

5、本地通知(類似于push通知)按home鍵到背景十秒後觸發:

    1.    UILocalNotification *notification=[[UILocalNotification alloc] init];   

    2.    if (notification!=nil) {   

    3.    NSLog(@">> support local notification");   

    4.    NSDate *now=[NSDate new];   

    5.    notification.fireDate=[now addTimeInterval:10];   

    6.    notification.timeZone=[NSTimeZone defaultTimeZone];   

    7.    notification.alertBody=@"該去吃晚飯了!";   

    8.    [[UIApplication sharedApplication].scheduleLocalNotification:notification];  

    9.    }

6、捕獲iphone通話事件:

    1.    CTCallCenter *center = [[CTCallCenter alloc] init];  

    2.    center.callEventHandler = ^(CTCall *call)   

    3.    {  

    4.    NSLog(@"call:%@", call.callState);  

    5.    }

7、iOS 4 引入了多任務支援,是以使用者按下 “Home” 鍵以後程式可能并沒有退出而是轉入了背景運作。如果您想讓應用直接退出,最簡單的方法是:在 info-plist 裡面找到 Application does not run in background 一項,勾選即可。

8、使UIimageView的圖像旋轉:

    1.    float rotateAngle = M_PI;  

    2.    CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);  

    3.    imageView.transform = transform;

9、設定旋轉的原點:

    1.    #import <QuartzCore/QuartzCore.h>

    2.    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];  

    3.    imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

10、實作自定義的狀态欄(遮蓋狀态欄):

    1.    CGRect frame = {{0, 0}, {320, 20}};  

    2.    UIWindow* wd = [[UIWindow alloc] initWithFrame:frame];  

    3.    [wd setBackgroundColor:[UIColor clearColor]];  

    4.    [wd setWindowLevel:UIWindowLevelStatusBar];  

    5.    frame = CGRectMake(100, 0, 30, 20);  

    6.    UIImageView* img = [[UIImageView alloc] initWithFrame:frame];  

    7.    [img setContentMode:UIViewContentModeCenter];  

    8.    [img setImage:[UIImage imageNamed:@"00_0103.png"]];  

    9.    [wd addSubview:img];  

    10.    [wd makeKeyAndVisible];  

    11.    [UIView beginAnimations:nil context:nil];  

    12.    [UIView setAnimationDuration:2];  

    13.    frame.origin.x += 150;  

    14.    [img setFrame:frame];  

    15.    [UIView commitAnimations];

11、在程式中實作電話的撥打:

    1.    //添加電話圖示按鈕   

    2.    UIButton *btnPhone = [[UIButton buttonWithType:UIButtonTypeCustom] retain];   

    3.    btnPhone.frame = CGRectMake(280,10,30,30);   

    4.    UIImage *image = [UIImage imageNamed:@"phone.png"];       

    5.    [btnPhone setBackgroundImage:image forState:UIControlStateNormal];   

    6.    //點選撥号按鈕直接撥号   

    7.    [btnPhone addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];   

    8.    [cell.contentView addSubview:btnPhone];  //cell是一個UITableViewCell   

    9.    //定義點選撥号按鈕時的操作   

    10.    - (void)callAction:(id)sender event:(id)event{   

    11.    NSSet *touches = [event allTouches];   

    12.    UITouch *touch = [touches anyObject];   

    13.    CGPoint currentTouchPosition = [touch locationInView:self.listTable];   

    14.    NSIndexPath *indexPath = [self.listTable indexPathForRowAtPoint: currentTouchPosition];   

    15.    if (indexPath == nil) {   

    16.    return;   

    17.    }   

    18.    NSInteger section = [indexPath section];   

    19.    NSUInteger row = [indexPath row];   

    20.    NSDictionary *rowData = [datas objectAtIndex:row];   

    21.    NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number為号碼字元串       

    22.    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //撥号   

    23.    }

12、更改iphone的鍵盤顔色:

1.隻有這2種數字鍵盤才有效果。UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

2. keyboardAppearance = UIKeyboardAppearanceAlert

    1.    - (void)textViewDidBeginEditing:(UITextView *)textView{  

    2.    NSArray *ws = [[UIApplication sharedApplication] windows];  

    3.    for(UIView *w in ws){  

    4.    NSArray *vs = [w subviews];  

    5.    for(UIView *v in vs)  

    6.    {  

    7.    if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"])  

    8.    {  

    9.    v.backgroundColor = [UIColor redColor];  

    10.    }  

    11.    }  

    12.    }

13、設定時區

    1.    NSTimeZone *defaultTimeZone = [NSTimeZone defaultTimeZone];  

    2.    NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];  

    3.    [NSTimeZone setDefaultTimeZone:tzGMT];

上面兩個時區任意用一個。

14、Ipad隐藏鍵盤的同時觸發方法。

    1.    [[NSNotificationCenter defaultCenter] addObserver:self  

    2.    selector:@selector(keyboardWillHide:)  

    3.    name:UIKeyboardWillHideNotification  

    4.      object:nil];  

    5.    - (IBAction)keyboardWillHide:(NSNotification *)note

15、計算字元串的字數

    1.    -(int)calculateTextNumber:(NSString *)text  

    2.    {  

    3.    float number = 0.0;  

    4.    int index = 0;  

    5.    for (index; index < [text length]; index++)  

    6.    {  

    7.    NSString *protoText = [text substringToIndex:[text length] - index];  

    8.    NSString *toChangetext = [text substringToIndex:[text length] -1 -index];  

    9.    NSString *charater;  

    10.    if ([toChangetext length]==0)  

    11.    {  

    12.    charater = protoText;  

    13.    }  

    14.    else   

    15.    {  

    16.    NSRange range = [text rangeOfString:toChangetext];  

    17.    charater = [protoText stringByReplacingCharactersInRange:range withString:@""];  

    18.    }  

    19.    NSLog(charater);  

    20.    if ([charater lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)  

    21.    {  

    22.    number++;  

    23.    }  

    24.    else   

    25.    {  

    26.    numbernumber = number+0.5;  

    27.    }  

    28.    }  

    29.    return ceil(number);  

    30.    } 

16.使得device長期電量,不鎖屏

UIApplication sharedApplication].idleTimerDisabled = YES;

17.ios6轉屏問題解決方法

原來的方法:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 

    2.    { 

    3.        return (interfaceOrientation == UIInterfaceOrientationPortrait); 

    4.    } 

    5.      

代替的方法:

    6.    -(BOOL)shouldAutorotate 

    7.    { 

    8.        return NO; 

    9.    } 

    10.     

    11.    -(NSUInteger)supportedInterfaceOrientations 

    12.    { 

    13.        return UIInterfaceOrientationMaskPortrait; 

    14.    } 

18 ,判斷是否有網絡連結

引入systemConfing framework 然後下載下傳Reachability. h 和Reachability.m 類,

實作

Reachability *networkReachability = [Reachability reachabilityForInternetConnection];   
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];    
if (networkStatus == NotReachable) {        
    NSLog(@"There IS NO internet connection");        
} else {        

     NSLog(@"There IS internet connection");        


    }        
}
           

19.隐藏狀态欄

或者

// iOS3.2+支援
[application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
      

 statusBarHidden屬性支援在iOS2.0+,setStatusBarHidden:animated:方法在iOS3.2中開始取消了,而采用了setStatusBarHidden:withAnimation:方法。

上述方法隻能實作在程式跳過loading(即啟動畫面)的時候才能隐藏狀态欄。如果想要在啟動畫面開始即隐藏狀态欄,則要修改app的info.plist檔案,新增UIStatusBarHidden鍵(Statusbar is initially hidden),其值是YES。

同理:對于狀态欄的顔色改變,也要分别從兩處着手,代碼[[UIApplicationsharedApplication]setStatusBarStyle:UIStatusBarStyleBlackOpaque];僅僅改變了啟動畫面之後的視圖上的狀态欄,要讓App應用在啟動畫面之時就改變預設顔色,則要修改info.plist檔案,新增UIStatusBarStyle鍵(Statusbar style),其值有Opaque black style、Transparent black style和預設的Graystyle。

20.隐藏nagivation bar

[self.navigationController setNavigationBarHidden:YES];      

21.隐藏頁籤tabbar

方法一:

[self.tabBarController.tabBar setHidden:YES];
      

此方法的問題:雖然tabBar欄被隐藏了,但該區域成一片空白區,無法被其他視圖使用。

方法二:

對于navigationController+tabBarController的結構,可以在push下一級的childController之前将childController的hidesBottomBarWhenPushed屬性設為YES。比如,可以在childController的初始化方法中做這件事,代碼如下:

iphone 開發小技巧(持續更新中)
1 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 

2 { 

3      self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 

4      if (self) { 

5         // Custom initialization.
6         self.hidesBottomBarWhenPushed = YES;

7     } 

8 return self;

9 }
      
iphone 開發小技巧(持續更新中)

方法三:

- (void)makeTabBarHidden:(BOOL)hide
 {
   if ( [self.tabBarController.view.subviews count] < 2 )
     {
        return;
   }
    UIView *contentView;
      
      if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
    {
       contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    }
    else
    {
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    }
     //    [UIView beginAnimations:@"TabbarHide" context:nil];
   if ( hide )
   {
        contentView.frame = self.tabBarController.view.bounds;        
   }
     else
    {
       contentView.frame = CGRectMake(self.tabBarController.view.bounds.origin.x,
                                      self.tabBarController.view.bounds.origin.y,
                                       self.tabBarController.view.bounds.size.width,
                                       self.tabBarController.view.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    }
    
    self.tabBarController.tabBar.hidden = hide;
   //    [UIView commitAnimations];    
 }

           

時機

- (void)viewWillAppear:(BOOL)animated 
{
      [self setFullScreen:YES];
 } 
- (void)viewWillDisappear:(BOOL)animated
 {
      [self setFullScreen:NO];
  } 
  - (void)setFullScreen:(BOOL)fullScreen 
{
    // 狀态條
      [UIApplication sharedApplication].statusBarHidden = fullScreen;
     // 導覽列
    [self.navigationController setNavigationBarHidden:fullScreen];
     // tabBar的隐藏通過在初始化方法中設定hidesBottomBarWhenPushed屬性來實作
  }
           

22.驗證

/*郵箱驗證 MODIFIED BY HELENSONG*/
       
-(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}      
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手機号以13, 15,18開頭,八個 \d 數字字元
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
//    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}
           
BOOL validateCarNo(NSString* carNo) 
{ 
    NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$"; 
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex]; 
    NSLog(@"carTest is %@",carTest); 
    return [carTest evaluateWithObject:carNo]; 
} 
           
23.UITextView 清空時鍵盤的改變
-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSMutableString *newValue = [textField.text mutableCopy];
    [newValue replaceCharactersInRange:range withString:string];
    if ([newValue length]== 0) {
        textField.returnKeyType=UIReturnKeyDone;
        [textField reloadInputViews];
    }
    else {
        textField.returnKeyType=UIReturnKeySearch;
        [textField reloadInputViews];
        
    }
    
    return YES;
}