IOS开发小Tips

(1)碰到报错:IBOutlet property has non-optional type UILabel

在Xcode6-beta版本碰到,    @IBOutlet var countryLabel : UILabel = nil这句话报错,改为    @IBOutlet var countryLabel : UILabel !即可


(2)         获取设备的参数

NSLog([[UIDevice currentDevice] name]); // Name of the phone as named by user

NSLog([[UIDevice currentDevice] uniqueIdentifier]); // A GUID like string 

NSLog([[UIDevice currentDevice] systemName]); // "iPhone OS" 

NSLog([[UIDevice currentDevice] systemVersion]); // "2.2.1" 

NSLog([[UIDevice currentDevice] model]); // "iPhone" on both devices 

NSLog([[UIDevice currentDevice] localizedModel]); // "iPhone" on both devices 

float version = [[[UIDevice currentDevice] systemVersion] floatValue]; 


(3)设置searchbar半透明提示字:PlaceHolder属性

[searchBarsetPlaceholder:@"Search"];


(4)给UIView设置点击事件

-(void)initCoverView{
    coverView.userInteractionEnabled=YES;//设置该view可以交互
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAdvancedSearchView:)];
    [coverView addGestureRecognizer:tapGesture];
}

下面实现方法showAdvancedSearchView:

- (void)showAdvancedSearchView:(UITapGestureRecognizer *)gesture{
    NSLog(@"!!!!  click cover view");
    
}

(5)去掉SearchBar边框

在SearchBar属性Bar Tint选择“Clear Color”即可。


(6)使用tableview时注意设置的大小,如果过大,则最后一行无法滑动显示


(7)textfield常用属性:

增加提示水印:textField.placeholder=@"用户名称";

改变return类型为Done: textField.returnKeyType=UIReturnKeyDone;

用于一次性清空输入内容的靠右小叉叉:textField.clearButtonMode=UITextFieldViewModeAlways;

(8)使用代码隐藏TextField软键盘

首先在使用界面的.h文件中加入UITextFieldDelegate声明;

然后设置代理:

            accountTextField=[[UITextFieldalloc]initWithFrame:CGRectMake(15,0,320,44)];

            accountTextField.delegate=self;

最后实现方法:

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

   if (accountTextField == textField) {

        [accountTextFieldresignFirstResponder];

    }

    return YES;

}


(9)自定义颜色(RGB)

[UIColorcolorWithRed:13/255.0green:68/255.0blue:137/255.0alpha:1.0];


(10)UIPickerView高度

宽度可以改变,但是PickerView的高度是定死的216像素,无法改变


(11) 网络推送notification最多能推送256字节,超过则不予以推送。

(12) 使用动画效果CATransition

    CATransition *animation = [CATransitionanimation];

    animation.duration =10.0f;

// 表示动画表示的时间开始结束缓慢,中间快

    animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];

// 这是动画类型,有很多种选择

//  kCATransitionMoveIn(覆盖原图)kCATransitionFade(淡出) kCATransitionReveal(从底部缓慢显示) kCATransitionPush(推出)

//  也可以这样表示 animation.type=@"";  

   /* 过渡效果
fade     //交叉淡化过渡(不支持过渡方向)
push     //新视图把旧视图推出去
moveIn   //新视图移到旧视图上面
reveal   //将旧视图移开,显示下面的新视图
cube     //立方体翻滚效果
oglFlip  //上下左右翻转效果
suckEffect   //收缩效果,如一块布被抽走(不支持过渡方向)
rippleEffect //滴水效果(不支持过渡方向)
pageCurl     //向上翻页效果
pageUnCurl   //向下翻页效果
cameraIrisHollowOpen  //相机镜头打开效果(不支持过渡方向)
cameraIrisHollowClose //相机镜头关上效果(不支持过渡方向)
*/

    animation.type=kCATransitionPush;

    animation.subtype =kCATransitionFromRight;

    [self.view.layeraddAnimation:animationforKey:@"animation"];

    [selftransitionFromViewController:rootViewController

                     toViewController:domainViewController

                             duration:1

                               options:UIViewAnimationCurveEaseInOut

                           animations:^(void){

                            }

                           completion:^(BOOL finished) {}];


(13) 使用pushViewController没效果

这个时候需要检查self.navigationController是否为nil,基本上无效就是因为navigationController为nil


(14) 打印CGRect

CGRect rx = [ UIScreen mainScreen ].bounds;

NSLog(@"%@",NSStringFromCGRect(rx));


(15) 图片使用问题及尺寸

Asset

iPhone 6 Plus (@3x)

iPhone 6 and iPhone 5 (@2x)

iPhone 4s (@2x)

iPad and iPad mini (@2x)

iPad 2 and iPad mini (@1x)

App icon

180 x 180

120 x 120

120 x 120

152 x 152

76 x 76

App icon for the App Store 

1024 x 1024

1024 x 1024

1024 x 1024

1024 x 1024

1024 x 1024

Launch file or image (required for all apps)

Use a launch file (see Launch Images)

1242*2208

For iPhone 6, use a launch file (see Launch Images)

750*1334

For iPhone 5, 640 x 1136

640 x 960

1536 x 2048 (portrait)

2048 x 1536 (landscape)

768 x 1024 (portrait)

1024 x 768 (landscape)

Spotlight search results icon (recommended)

120 x 120

80 x 80

80 x 80

80 x 80

40 x 40

Settings icon (recommended)

87 x 87

58 x 58

58 x 58

58 x 58

29 x 29

Toolbar and navigation bar icon (optional)

About 66 x 66

About 44 x 44

About 44 x 44

About 44 x 44

About 22 x 22

Tab bar icon (optional)

About 75 x 75 (maximum: 144 x 96)

About 50 x 50 (maximum: 96 x 64)

About 50 x 50 (maximum: 96 x 64)

About 50 x 50 (maximum: 96 x 64)

About 25 x 25 (maximum: 48 x 32)

Default Newsstand cover icon for the App Store (required for Newsstand apps)

At least 1024 pixels on the longest edge

At least 1024 pixels on the longest edge

At least 1024 pixels on the longest edge

At least 1024 pixels on the longest edge

At least 512 pixels on the longest edge

Web clip icon (recommended for web apps and websites)

180 x 180

120 x 120

120 x 120

152 x 152

76 x 76

讨厌的是,4系列竟然也使用@2x的图片,(但是3GS使用的是无后缀的图片)

所以无法区分,只能在项目中添加代码处理4系列的图片!


(16) 将testFiled设置为密码输入格式

test.secureTextEntry=YES;


(17) 解决重用TableViewCell时内容错位问题

获取Cell的方法使用如下:

//设置TableViewCell具体样式

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell =nil;

   staticNSString *TableViewCellIdentifier =@"MyCells";

    cell=[tableViewcellForRowAtIndexPath:indexPath];//!!!!!!这一句话Important!!!!!!

   if (cell ==nil) {

        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:TableViewCellIdentifier];

    }

}

(18) UILabel换行

    headerLabel.lineBreakMode=UILineBreakModeWordWrap;

    headerLabel.numberOfLines=0;

    headerLabel.text=@"1231323123123123123 \n 1021912920192309832098234098 \n 23423082304982";

注意顺序不要变,同时注意headerLabel的大小至少有三行,足以显示所有的字


(19)设置TableViewCell不能点击

cell.selectionStyle = UITableViewCellSelectionStyleNone;


(20) Alert按钮相应事件

创建Alert:

UIAlertView *updatedAlert=[[UIAlertViewalloc]initWithTitle:nilmessage:@"LOL" delegate:selfcancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];

[updatedAlertshow];


首先在.h文件中添加<UIAlertViewDelegate>

然后在.m文件中实现如下方法即可:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSLog(@" button index=%d is clicked.....", buttonIndex);

}

(21) 设置UIWebView背景透明

UIWebView webView=[[UIWebView alloc]init];

[webView setBackgroundColor:[UIColor clearColor]];

webView.opaque=NO;//这句非常重要~!!!!!!!!


(22) 在项目内发送EMail

1. 在项目内导入框架MessageUI.framework;

2..h文件如下

  1. #import <UIKit/UIKit.h>   
  2. #import <MessageUI/MFMailComposeViewController.h>   
  3.   
  4. @interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>   
  5.   
  6. @end  
3. 实现文件如下

  1. #import <MessageUI/MessageUI.h>  
  2. sendMailViewController.m文件的实现:  
  3. - (void)viewDidLoad  
  4. {  
  5.     UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];  
  6.     button.frame = CGRectMake(0, 40, 320, 50);  
  7.     [button setTitle: @"Mail" forState: UIControlStateNormal];  
  8.     [button addTarget: self action: @selector(sendEMail) forControlEvents: UIControlEventTouchUpInside];  
  9.     [self.view addSubview: button];  
  10. }  
  11.   
  12. - (void) alertWithTitle: (NSString *)_title_ msg: (NSString *)msg   
  13. {  
  14.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_title_   
  15.                                                     message:msg   
  16.                                                    delegate:nil   
  17.                                           cancelButtonTitle:@"确定"   
  18.                                           otherButtonTitles:nil];  
  19.     [alert show];  
  20.     [alert release];  
  21. }   
  22.   
  23. //点击按钮后,触发这个方法  
  24. -(void)sendEMail   
  25. {  
  26.     Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));  
  27.       
  28.     if (mailClass != nil)  
  29.     {  
  30.         if ([mailClass canSendMail])  
  31.         {  
  32.             [self displayComposerSheet];  
  33.         }   
  34.         else   
  35.         {  
  36.             [self launchMailAppOnDevice];  
  37.         }  
  38.     }   
  39.     else   
  40.     {  
  41.         [self launchMailAppOnDevice];  
  42.     }      
  43. }  
  44. //可以发送邮件的话  
  45. -(void)displayComposerSheet   
  46. {  
  47.     MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];  
  48.       
  49.     mailPicker.mailComposeDelegate = self;  
  50.       
  51.     //设置主题  
  52.     [mailPicker setSubject: @"eMail主题"];  
  53.       
  54.     // 添加发送者  
  55.     NSArray *toRecipients = [NSArray arrayWithObject: @"first@example.com"];  
  56.     //NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];  
  57.     //NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com", nil];  
  58.     [mailPicker setToRecipients: toRecipients];  
  59.     //[picker setCcRecipients:ccRecipients];      
  60.     //[picker setBccRecipients:bccRecipients];  
  61.       
  62.     // 添加图片  
  63.     UIImage *addPic = [UIImage imageNamed: @"123.jpg"];  
  64.     NSData *imageData = UIImagePNGRepresentation(addPic);            // png  
  65.     // NSData *imageData = UIImageJPEGRepresentation(addPic, 1);    // jpeg  
  66.     [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"123.jpg"];  
  67.       
  68.     NSString *emailBody = @"eMail 正文";  
  69.     [mailPicker setMessageBody:emailBody isHTML:YES];  
  70.       
  71.     [self presentModalViewController: mailPicker animated:YES];  
  72.     [mailPicker release];  
  73. }  
  74. -(void)launchMailAppOnDevice  
  75. {  
  76.     NSString *recipients = @"mailto:first@example.com&subject=my email!";  
  77.     //@"mailto:first@example.com?cc=second@example.com,third@example.com&subject=my email!";  
  78.     NSString *body = @"&body=email body!";  
  79.       
  80.     NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];  
  81.     email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];  
  82.       
  83.     [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];  
  84. }  
  85. - (void)mailComposeController:(MFMailComposeViewController *)controller   
  86.           didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error   
  87. {  
  88.     NSString *msg;  
  89.       
  90.     switch (result)   
  91.     {  
  92.         case MFMailComposeResultCancelled:  
  93.             msg = @"邮件发送取消";  
  94.             break;  
  95.         case MFMailComposeResultSaved:  
  96.             msg = @"邮件保存成功";  
  97.             [self alertWithTitle:nil msg:msg];  
  98.             break;  
  99.         case MFMailComposeResultSent:  
  100.             msg = @"邮件发送成功";  
  101.             [self alertWithTitle:nil msg:msg];  
  102.             break;  
  103.         case MFMailComposeResultFailed:  
  104.             msg = @"邮件发送失败";  
  105.             [self alertWithTitle:nil msg:msg];  
  106.             break;  
  107.         default:  
  108.             break;  
  109.     }  
  110.       
  111.     [self dismissModalViewControllerAnimated:YES];  
  112. }  

(23) 使用MFMailComposeViewController发送邮件,改变其NavigationBar的背景

尝试了很多种方法都不成功,最后在AppDelegate.m方法中的didFinishLaunchingWithOptions方法中添加如下代码即可~!!!

    [[UINavigationBarappearance]setBackgroundImage:[UIImageimageNamed:@"navigationBarBackground.png"]forBarMetrics:UIBarMetricsDefault];


(24)在didFinishedLaunchingWithOptions方法设置text颜色时,如果需要使用阴影颜色,记得设置阴影偏移参数

    [[UINavigationBarappearance]setTitleTextAttributes:

     [NSDictionarydictionaryWithObjectsAndKeys:

      [UIColor whiteColor],UITextAttributeTextColor,

      [UIColor grayColor],UITextAttributeTextShadowColor,

      [NSValue valueWithUIOffset:UIOffsetMake(0, -1)],UITextAttributeTextShadowOffset,

      [UIFont boldSystemFontOfSize:20.0],UITextAttributeFont,nil]];


(25) 在ScrollView中使用UIWebView

#import <Foundation/Foundation.h>
#import "TNCViewController_iPhone.h"
@interface TNCViewController_iPhone ()

@end
@implementation TNCViewController_iPhone
UIScrollView *scrollView;
UIWebView *tncWebView;
UIImageView *TNCbackgroundImageView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect rx = [ UIScreen mainScreen ].bounds;
    float height=rx.size.height;
    height=self.view.bounds.size.height;
    rx.size.height=height-49-64;
    scrollView = [[UIScrollView alloc] initWithFrame:rx];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.delegate = self;

    [scrollView flashScrollIndicators];
    scrollView.directionalLockEnabled = YES;
    
    TNCbackgroundImageView=[[UIImageView alloc]initWithFrame:rx];
    [TNCbackgroundImageView setImage:[UIImage imageNamed:@"contentBackground.png"]];
    [self.view addSubview:TNCbackgroundImageView];
    
    [self.view addSubview:scrollView];
    
    tncWebView=[[UIWebView alloc]initWithFrame:rx];
    
    //获取文件路径
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"tnc_chi" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [tncWebView setBackgroundColor:[UIColor clearColor]];
    [tncWebView loadRequest:request];
    tncWebView.opaque=NO;
    scrollView.contentSize=tncWebView.frame.size;
    [scrollView addSubview:tncWebView];
    [tncWebView release];

}
@end

(26) Label中文字居中属性

NSTextAlignmentCenter


(27) 获取连接的Wifi名称

1. 在.h文件中添加      #import<SystemConfiguration/CaptiveNetwork.h>

2. 方法体:

NSString *wifiName=nil;
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        NSLog(@"!!!!!!  No Wifi Connect");
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);


注意,上面这个方法拿到的是包括wifi名字和地址在内的数值,如果单纯的只是希望Wifi用户名,可以这样处理:

    NSString *wifiName = @"Not Found";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            wifiName = [dict valueForKey:@"SSID"];
        }
    }
    NSLog(@"wifiName:%@", wifiName);

(28)获取SIM卡中的MCC和MNC

1. 在.h文件中添加 

#import <CoreTelephony/CTCarrier.h>

#import <CoreTelephony/CTTelephonyNetworkInfo.h>


2.在代码中

    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfoalloc]init];

    CTCarrier *carrier = [infosubscriberCellularProvider];

    

   NSString *code = [carriermobileNetworkCode];

   NSString *country=[carriermobileCountryCode];

   NSString *carrierName=[carriercarrierName];

   NSString *iosCountryCode=[carrierisoCountryCode];

    NSLog(@"!!!!!!!  code    %@",code);

    NSLog(@"!!!!!!!  countrey    %@",country);

    NSLog(@"!!!!!!   carrier Name    %@",carrierName);

    NSLog(@"!!!!!  iosCountrycoede   %@",iosCountryCode);


(29)使用NSNotification在两个文件之间传递参数(包括AppDelegate)

1. 在接收的文件中定义一个NotificationCenter,当接受到@“shake”时,调用方法 eraseView

    [[NSNotificationCenterdefaultCenter]addObserver:self                                                           selector:@selector(eraseView) name:@"shake" object:nil];

2. 实现方法eraseView

-(void) eraseView

{

    NSLog(@"!!!!!!!!  getNotification !!");

    wifiNameLabel.text=@"YEYEEYEYEYEYE";

}

3. 在发出文件中:

        [[NSNotificationCenterdefaultCenter]postNotificationName:@"shake" object:self];


(30)使用Reachability检测Wifi使用情况(动态检测开启和关闭)

要注意~!!!Reachablity3.0以上的版本才支持ARC!所以要根据你的项目需求导入不同的Reachability

1. 在项目中导入 Reachability.h 和 Reachability.m 

2. 在项目的framework中导入SystemConfiguration.framework

3.在需要使用的.h文件中  #import"Reachability.h"

4.在程序中实现:

    Reachability *r = [ReachabilityreachabilityWithHostName:@"www.apple.com"];

    switch ([rcurrentReachabilityStatus]) {

        caseNotReachable://No Wifi

           //没有网络连接

           break;

        caseReachableViaWWAN:

           //使用3G网络

            NSLog(@"!!!!!  Use  3G");

           break;

        caseReachableViaWiFi:

           //使用WiFi网络

            NSLog(@"!!!!$$$$$$$$$$$$$$!!!  use WIFI");

           break;

    }


例如在IOS7中,可以使用快捷上拉栏开启和关闭Wifi功能,所以要在appDelegate文件中对动态开启关闭Wifi功能进行检测

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

//...

    [[NSNotificationCenterdefaultCenter]addObserver:self

                                            selector:@selector(reachabilityChanged:)

                                                name:kReachabilityChangedNotification

                                              object:nil];

    hostReach = [[ReachabilityreachabilityWithHostName:@"www.google.com"]retain];

    [hostReachstartNotifier];

//...

}

然后在方法reachbilityChanged中监听Wifi状态的改变

- (void)reachabilityChanged:(id)note {

//    Reachability* curReach = [note object];


    NSParameterAssert([hostReachisKindOfClass: [Reachabilityclass]]);

    NetworkStatus status = [hostReachcurrentReachabilityStatus];

    [[NSNotificationCenterdefaultCenter]postNotificationName:@"changeText"

                                                       object:self];

   if (status ==NotReachable) {

       UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"AppName"

                                                       message:@"NotReachable"

                                                      delegate:nil

                                             cancelButtonTitle:@"YES"otherButtonTitles:nil];

        [alertshow];

        [alertrelease];

        [[NSNotificationCenterdefaultCenter]postNotificationName:@"changeText"

                                                           object:self];

    }else {


    }


}


(32) UI平移动画效果

    [UIViewanimateWithDuration:0.5animations:^{

        [preferButtonsetTransform:CGAffineTransformMakeTranslation(preferbtnRx.origin.x-40,preferbtnRx.origin.y)];

        [locationButtonsetTransform:CGAffineTransformMakeTranslation(preferbtnRx.origin.x-40,preferbtnRx.origin.y)];

    }];

其中, preferbtnRx是CGRect (没有初始化的),该效果是这两个按钮向左水平平移40距离



(34)只改变NavigationBar返回键的内容,而不改变其样式

注意,要在其父类中实现下面代码!

    UIBarButtonItem *backbutton = [[UIBarButtonItemalloc]init];

    backbutton.title =@"返回";

    self.navigationItem.backBarButtonItem = backbutton;

    [backbuttonrelease];


如果是实现按钮的自定义,关键字是self.navigationItem.left.......


  (35) 新建项目在Iphone5运行时出现上下两条黑边,只要添加尺寸为320*568的黑色图片即可(项目默认3.7寸屏幕),且命名为Default-568h@2x.png


 (36) 实现数字小时钟

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize timeLabel;//It's a UILabel

NSTimer *timer;
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setTime];
    timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setTime:) userInfo:nil repeats:YES];
}

-(void)setTime:(id)sender{
    NSDate *curtime = [NSDate date];
    NSDateFormatter *formatterCur1 = [[NSDateFormatter alloc] init];
    [formatterCur1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timestr1 = [formatterCur1 stringFromDate:curtime];
    timeLabel.text=timestr1;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//页面将要进入前台,开启定时器
-(void)viewWillAppear:(BOOL)animated
{
    //开启定时器
    [timer setFireDate:[NSDate distantPast]];
}

//页面消失,进入后台不显示该页面,关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [timer setFireDate:[NSDate distantFuture]];
}

@end

(37) 禁止横屏

在AppDelegate中添加:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

    returnUIInterfaceOrientationMaskPortrait;

}


(38)popoverController只能在iPad上使用,如果想要在iPhone上使用,参考链接的代码  

http://download.csdn.net/detail/eduask_xia/4287865


(40)使用sqlite3执行查询语句

其中,databaseX和databaseY是double类型,表testing中包含x,y,z,en,ch数值,x,y,z为int,en,ch为text

NSString * selectSql = [NSStringstringWithFormat:@"select * from testing where (abs(x-%f)<=250) and (abs(y-%f)<=250)",databaseX,databaseY];

            NSLog(@"dataExisted query_sql:%@",selectSql);            

           sqlite3_stmt *statement;

           if (sqlite3_prepare_v2(database, [selectSqlUTF8String], -1, &statement,nil)==SQLITE_OK)

            {

               while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK SQLITE_ROW

                {

                   int x=sqlite3_column_int(statement,0);

                   int y=sqlite3_column_int(statement,1);

                   int z=sqlite3_column_int(statement,2);

                    NSString *en=[[NSStringalloc]initWithCString:(char *)sqlite3_column_text(statement,3)encoding:NSUTF8StringEncoding];

                    NSString *ch=[[NSStringalloc]initWithCString:(char *)sqlite3_column_text(statement,4)encoding:NSUTF8StringEncoding];

                    

                    NSLog(@"row>>x %i, y %d,z %d, en>> %@, ch  %@",x,y,geo_ref,dn_en,dn_ch);

                }

            }


(42)获得系统时间

    NSDate * senddate=[NSDatedate];

    NSDateFormatter *dateformatter=[[NSDateFormatteralloc]init];

    [dateformattersetDateFormat:@"YYYYMMdd-HH-mm-ss"];

   NSString * dataString=[dateformatterstringFromDate:senddate];


要注意!!重要事情说三遍!重要事情说三遍!重要事情说三遍!

如果单纯是NSDate date拿到的时间是格林尼治时间,但是经过dateformatter转变之后,String就变成了系统时间~!相当神奇!

(43)去掉NSString首尾空格

[signalStrengthLabel.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];


(44)NSMutableString添加URL参数

    NSMutableString *urlString=[[NSMutableStringalloc]initWithString:requestUrl];//requestUrl="http//xx.xx.xx.xx/xxxx/xx.php"

    [urlStringappendString:@"?"];

    [urlStringappendFormat:@"version=%i",version];//version=1

    [urlStringappendFormat:@"&Date=%@",date];//data =@"20141209"

    [urlStringappendFormat:@"&Latitude=%.7f",latitude];//latitude=23.1214134


(45)使用UTF-8编码NSString

[NSString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];


(46)设置带有NavigationBar的跳转页面标题
这时候只能设置

    [self.navigationItemsetTitle:@"TESTTEST"];

别的属性都不管用



(47)        程序崩溃 IOS EXC_BAD_ACCESS

这个问题是最不好排查的,连NSLog都不管用,因为在控制台上根本看不到是那个Object出了问题

90%的情况都是因为对某个已经释放的类进行release操作


(48)      IOS时间转化为NSString

 NSDate* today = [NSDatedate];

   NSLog(@"%@",today);

   NSDateFormatter*df = [[NSDateFormatteralloc]init];

   [dfsetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

 NSString* s1 = [dfstringFromDate:today];


(49)    使用sqlite3时提示database is locked解决方法

我在这里并没有使用多线程,我的问题是select语句没有进行reset操作

        

       sqlite3_reset(selectStmt);

       if(selectStmt)sqlite3_finalize(selectStmt);

添上这两行就好


(50)    UIActionSheet简单使用方法

1. 在.h文件中引用ActoinSheetDelegate

<UIActionSheetDelegate>

2. 实现ActionSheet

 UIActionSheet *sheet=[[UIActionSheetalloc]initWithTitle:nildelegate:selfcancelButtonTitle:@"cancel"destructiveButtonTitle:[NSString stringWithFormat:@"Test1 %@",showContent]otherButtonTitles:[NSStringstringWithFormat:@"Test2 %@",showContent],[NSStringstringWithFormat:@"Test3 %@",showContent],nil];

 [sheetshowInView:self.view];


3. ActionSheet按钮的监听

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

   if (buttonIndex ==0) {

       NSLog(@"00000");

    }elseif (buttonIndex ==1) {

       NSLog(@"11111");

    }elseif(buttonIndex ==2) {

       NSLog(@"222222");

    }elseif(buttonIndex ==3) {

       NSLog(@"33333");

    }

    

}


(51)   删除本地文件

            NSFileManager *fileManager=[NSFileManager defaultManager];
            NSError *errorFileDelete;
            if ([fileManager fileExistsAtPath:localFilePath]){
                [fileManager removeItemAtPath:localFilePath error:&errorFileDelete];
            }


(52)   UIImage显示图片用法

1. 显示已经导入项目的资源

UIImage *image=[UIImage imageNamed:@"PictureName"];


2. 显示绝对路径的图片(用于显示下载图片后储存在本地的图片)

 UIImage *personImage=[UIImageimageWithContentsOfFile:photoPath];


3. 显示URL地址图片

NSURL *url = [NSURL URLWithString:@"图片地址"]; 
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]]; 


(53)   UIImage实现圆形图片效果

            UIImage *Image=[UIImage imageWithContentsOfFile:@“XXXXX”];
            UIImage *scaledImage = [Image scaleToSize:CGSizeMake(100, 100)];
            
            Icon.image=scaledImage;
            [Icon.layer setCornerRadius:scaledImage.size.width/2];
            [Icon.layer setMasksToBounds:YES];

其中scaledImage的scaleToSize中的参数能够决定图片四个角的弧度,弧度越大,越接近圆形

另外Icon是UIImageView


(54) 页面左右滑动手势监听----即手指向左或向右滑动时,页面翻页效果

1. ViewdidLoad中添加代码:

    UISwipeGestureRecognizer *leftSwitch=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(switchLeft:)];
    leftSwitch.direction=UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:leftSwitch];
    
    
    UISwipeGestureRecognizer *rightSwitch=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(switchRight:)];
    rightSwitch.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwitch];
    


2. 在类中添加代码:

- (void)switchLeft:(UISwipeGestureRecognizer *)sender
{
    [self.myNavController switchPageTo:0];
}

- (void)switchRight:(UISwipeGestureRecognizer *)sender
{
<pre name="code" class="objc">    [self.myNavController switchPageTo:2];
}

 

(55) pushViewController动画代码:

CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.contentView.layer addAnimation:transition forKey:nil];


(56) 在ARC模式中使用delegate应该如下:

  __strong NSObject <PageDelegate> *pageDelegate;
@property (retain, nonatomic) id pageDelegate;


(57) 打印BOOL值方法

    NSLog(@"isON:%@",isEnable?@"YES":@"NO");


(58) 计算可变UILabel的行数

其中在此之前label已经实例化

- (int)lineCountForLabel:(UILabel *)label {
    CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX);
    CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap];
    
    return ceil(size.height / label.font.lineHeight);
}


(59) 限制TextView输入字数

首先设置了textView.delegate=self

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString *new=[textView.text stringByReplacingCharactersInRange:range withString:text];
    //To get the maxture of text
    int max=[StringUtil getMessageMaxNumber:text];
    NSInteger res=max-[new length];
    if (res>=0){
        return YES;
    } else {
        NSRange rg={0,[text length]+res};
        if (rg.length>0) {
            NSString *s=[text substringWithRange:rg];
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
}


(60)          textfield中监听回车事件

- (BOOL) textfieldShouldReturn:(UITextfield) textField{

    return YES;

}


(61)   UITextAlignmentCenter在6.0中被弃用

改为NSTextAlignmentCenter即可


(62)    重写Navigationbar的Back方法

其实不算是重写,因为找不到这个方法来覆盖,所以先自定义一个UIBarButtonItem,添加方法,然后将其设置为self.navigationItem.leftButton而非BackButton,然后再自定义的方法里添加想要的效果即可。


(63)     自定义UIBarButtonItem背景图

初始化的方法为


UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithImage.........];

但是不成功,显示出来的item为橙色(网上也有蓝色显示的)

原因在于Image尺寸貌似被压缩到最小了,所以看不到。

应该这样设置:

UIImage *image=[UIImage imagenamed:@....];

image=[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];


(64)     IOS模拟器出现FBSOpenApplicationErrorDomain, code=4 错误

选中IOS模拟器,然后iOS Simulator -> Reset Content and Settings.....即可


(65)判断APP是否在设备上首次安装
在AppDelegate方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加下面片段片段:

  if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstInstall"]) {
        NSLog(@"第一次启动!");
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstInstall"];
    } else {
        NSLog(@"非第一次启动");
    }


(66)使用storyboard,使用代码改变启动初始页面(配合检查是否初次安装该APP,决定是否显示引导动画)

在AppDelegate方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加下面片段片段:

NSString *startPageId=@"";
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstInstall"]) {
        //push welcome page
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstInstall"];
        startPageId=@"WelcomePageIdentifier";
    } else {
        NSLog(@"非第一次启动");
        startPageId=@"BookTabbarIdentifier";
    }
    self.window.rootViewController=[self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:startPageId];
    
    return YES;

说明:
在storyboard里面,给引导页面WelcomePageViewController添加了Storyboard ID  “WelcomePageIdentifier”
给使用界面TabbarController添加了Storyboard ID “BookTabbarIdentifier”
上述代码的逻辑是:如果是很初次安装,那么App的起始界面就是WelcomePage,否则就以TabbarController作为rootView界面


(67) 使用代码退出App(使用动画效果,否则看上去像闪退)

    NSLog(@"Clicked Cancel");

    AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;

    UIWindow *window=appDelegate.window;

    

    [UIView animateWithDuration:2.0 animations:^{

        window.alpha=0.0;

        window.frame=CGRectMake(0, window.bounds.size.width, 0, 0);

    } completion:^(BOOL finished){

        exit(0);

    }];

(68)  关掉某个文件的ARC模式
在Build Phases中搜索某文件的名字,选中一个/几个后回车,出现输入框,输入-fno-objc-arc,回车即可


(69)   获取系统时间

NSDate *currentTime=[NSDate date];
NSCalendar *calender=[NSCalendar currentCalendar];
unsigned int unitFlags=NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit;
NSDateComponents *dateComponent=[calender components:unitFlags fromDate:currentTime];
int year=[dateComponent year];
int month=[dateComponent month];
int day=[dateComponent day];
NSString *sTime=[NSString stringWithFormat:@"%d%d%d",year,month,day];
NSLog(@"Current time:%@",sTime);

如果需要精确到时,分,秒的话,在unitFlags后面继续添加代码: | NSHourCalendarUnit| NSMinuteCalendarUnit|NSSecondCalendarUnit;

然后再获取时分秒
int hour = [dateComponent hour];
int min = [dateComponent minute];
int sec = [dateComponent second];

即可


(70)    使用代码绘制渐变颜色(由上至下渐变)
 	CAGradientLayer *gradient = [CAGradientLayer layer];
	gradient.frame = CGRectMake(0, 0, 宽, 高);
	gradient.colors = [NSArray arrayWithObjects:
	                       (id)[UIColor blackColor].CGColor,
	                       (id)[UIColor grayColor].CGColor,
	                       (id)[UIColor blackColor].CGColor,
	                        nil];
	[self.view.layer insertSublayer:gradient atIndex:0];

(71)     如何将用户发送过来的crash日志中二进制码符号化(解析crash文件报错行)
以项目名为Test.app为例
1. 将拿到的crash日志改为后缀名为.crash的文件
2. 打开Xcode,Window, Organazier, 选中Test文件,右键,Show in Finder, 选中显示的Test.xcarchive,右键,显示包含内容,将显示的Test.app.dSYM拷贝出来
3. 将你build的IPA文件和刚才找到的.dSYM文件以及用户发送过来的.crash文件放置在同一个文件夹内
4. Xcode,Window,Device,(这个时候要连接设备),选择view logs,等待Xcode将设备的所有Log读取完毕之后,将用户的Crash文件拖拽到Logs当中,就可以看到看不明白的二进制码被符号化成相应的方法,类别,出错的行数等。

(72)     延迟几秒调用某个方法
直接使用下面代码即可,完全不需要使用定时器
即:定时器使用一定是为了某个重复调用
[self performSelector:@selector(setTime:) withObject:nil afterDelay:20.0];

然后在方法 - (void) setTime:(id)sender 中完成需要的动作即可


(73)      SQL中limit offset用法
举例说明:
select * from test where xx=? order by XX desc limit 10 offset 20
说明跳过前20条记录,开始取10条记录


(74)       使用Delegate时报错Cannot find protocal ......
A类中定义了protocal,想要在B类中使用,出现这个问题是因为两个类的.h文件相互import,取消掉其中一个即可


(75)       使用TableView必须实现的方法
#pragma TableView
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return [resourceArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Identifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }
//    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
//    NSString *titleString=[resourceArray objectAtIndex:indexPath.row];
//    label.text=titleString;
    
    return cell;
}

(76)        自定义使用Log(如PLog)并控制其打印
首先,创建一个.pch文件,命名规范为: 项目名称_Prefix.pch
然后将下面的代码拷贝到新文件中:
#define DEBUG 1
#ifdef DEBUG
#define PLog(...) NSLog(__VA_ARGS__)
#define debugMethod()NSLog(@"%s",__func__)
#else
#define NSLog(...)
#define debugMethod
#endif

然后会用PLog打印,如果想要关闭,那么将第一行#define DEBUG 1注销掉即可


(77)         点击Button后修改其标题,修改一瞬间后变回原来的标题
这是个很纠结的问题,我折腾了一下午,不能单纯的xxButton.titleLabel.text=@""这样修改,而应该是:
setTitle:ForState:UIControlStateNormal这样来设置才能达到需要的效果


(78)           发邮件、打电话
邮件:
        NSString *mailAddress=@"mailto:abc@clare.com";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailAddress]];

电话:
    NSString *callNumber=@"tel:12345678";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callNumber]];

(79)          ios项目引入第三方framework(如facebook)
引入第三方的framework方法和内部库一致,但是要注意必须将framework拷贝到项目文件夹内

(80)          Storyboard button设置圆角
选中Button, 在右边的编辑框中找到User Defined Runtime Atributes(点击菜单栏第三个按钮可看到)
点击“+”添加属性“layer.cornerRadius”,Type选择Number,然后填写Value值,默认按钮高度的话,value是5就有一个小圆角,慢慢试吧
要注意的是,如果该Button添加了图片作为背景,那么单纯设置layer.cornerRadius则没有作用,还需要多添加一个设置:setMasksToBounds YES 才会起作用


(81)          Label文字添加下划线
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString: [NSString stringWithFormat:@"Forget Password?"]];
    NSRange contentRange = {0,[content length]};
    [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range:contentRange];
    Label.attributedText = content;

(82)          Storyboard跳转后,如何传值
利用Segue在Storyboard的两个ViewController跳转时传值
1. 先连线好跳转,并选择Modal或Push模式
2. 点击连线(Segue),并在Identifier中给其命名
3.实现下面代理方法
# pragma Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"MobileSegue"]) {
        id sendSegue=segue.destinationViewController;
        [sendSegue setValue:@"Mobile" forKey:@"type"];
    } else if ([[segue identifier] isEqualToString:@"EmailSegue"]){
        id sendSegue=segue.destinationViewController;
        [sendSegue setValue:@"Email" forKey:@"type"];
    }
    
}


//EmailSegue/MobileSegue 就是你定义的Segue Identifier

(83)           设置键盘类型
如果需要动态设置键盘类型,可以参考下面代码
否则在storyboard上就可以选择textfield或textview的键盘类型,回车键类型等
 TextIP1.keyboardType = UIKeyboardTypeNumberPad;

UIKeyboardTypeAlphabet(Alphabet字母)
UIKeyboardTypeASCIICapable
UIKeyboardTypeDefault

2、数字键盘
UIKeyboardTypeDecimalPad (Decimal十进制)

3、电子邮箱键盘
UIKeyboardTypeEmailAddress

4、没有符号的英文键盘
UIKeyboardTypeNamePhonePad

5、没有小数点的数字键盘
UIKeyboardTypeNumberPad

6、全键盘的数字键盘
UIKeyboardTypeNumbersAndPunctuation

7、带符号的数字键盘
UIKeyboardTypePhonePad

8、推特键盘
UIKeyboardTypeTwitter

(84)            iPhone6/6s 模拟器键盘不弹出解决方法

在xcode6中, 模拟器中的键盘和电脑的键盘可以进行绑定or解除绑定,打开模拟器,在最上面的菜单栏中,选择hardware,然后选择keyboards,有三个选项, 依次都勾选就行了。(注意:第三个选项在点击之后,实际已勾上了,但显示未勾上,但实际已经奏效了,这可能是xcode6的一个显示上的bug)



(85)        监听Textfield输入内容变化
    [self.firstTextF addTarget:self
                       action:@selector(textFieldDidChange:)
             forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange:(id)sender
{
    NSLog(@"%@", self.firstTextF.text);
    
}

(86)        转菊花插件的使用UIActivityIndicatorView
使用方式就是
UIActivityIndicatorView *testActivityIndicator = [UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]];
testActivityIndicator.center = CGPointMake(100.0f, 100.0f);//只能设置中心,不能设置大小
[testActivityIndicator setFrame = CGRectMack(100, 100, 100, 100)];//不建议这样设置,因为UIActivityIndicatorView是不能改变大小只能改变位置,这样设置得到的结果是控件的中心在(100,100)上,而不是和其他控件的frame一样左上角在(100, 100)长为100,宽为100.
[self addSubview:testActivityIndicator];
testActivityIndicator.color = [UIColor redColor]; // 改变圈圈的颜色为红色; iOS5引入
[testActivityIndicator startAnimating]; // 开始旋转
[testActivityIndicator stopAnimating]; // 结束旋转
[testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏

(87)        自定义时间的倒计时
其实也是使用了Timer,可以参考之前的Timer的例子
重点是每秒调用的方法不再是获取当前时间,以倒数30分钟为例,
设置int counter=1800;(1800S)
int minute =counter/60;
int second=counter%60;
然后将minute和second显示出来即可

(88)        使用presentViewController 跳转黑屏
在ios8中使用[self presentViewController:controller animated:YES completion:^{}];跳转后黑屏
主要是因为使用了storyboard,然后还使用从前的方法获取Controller alloc init则无法与storyboard上的ViewController联系在一起
所以这个时候要使用下面的方法获取controller:

mainViewController *mainView=[self.storyboard instantiateViewControllerWithIdentifier:@ "ID" ];
然后再跳转即可

(89)         ScrollView滚动到指定位置
    CGPoint scrollPoint=CGPointMake(scrollViewRect.size.width, 0);
    [scrollView setContentOffset:scrollPoint animated:YES];

(90)          App注册Notification并获取其Token
1. 首先注册App的Profile的时候记得选择PushNotification类型的,否则不行
2. 代码部分全部在AppDelegate中完成
(1) 注册Notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FBLoginView class];
    
    //get stored missing call count-设置提醒标记
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    
    
    //Register Notification
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        // Register for iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        
        [application registerForRemoteNotifications];
    }
    else
    {
        // Register for iOS < 8 Notifications
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }
    
    return YES;
}


(2) 获取Token
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    NSLog(@"设备令牌: %@", deviceToken);
    NSString *tokeStr = [NSString stringWithFormat:@"%@",deviceToken];
    if ([tokeStr length] == 0) {
        return;
    }
}



- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
    NSLog(@"获得令牌失败: %@", error);
}

(91)           读取plist文件内容(与项目的info.plist处于同级文件夹内)
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];  
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];  
    NSLog(@"%@", data);//直接打印数据。  

plist名为plistdemo.plist
重要事情说三遍!重要事情说三遍!重要事情说三遍!!
用上述方法初始化plist文件的时候,要保证里面已经有内容了!否则无论如何都写不进去,因为文件还没有创建啊!他是nil啊!
所以要判断data是否为nil,如果为nil则初始化NSMutableDictionary的时候直接塞数据进去即可

然后[plistDic writeToFile:filePath atomically:YES];就可以写进去了

另外还有一个拿到路径的方法,貌似这个方法只能读,不能写,因为[NSBundle mainBundle]拿到的路径是只读的
   Boolean result = false;
    NSString *filePath = [[self libraryPath] stringByAppendingPathComponent:@"test.plist"];
    
/*    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }*/
    
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    
    [plistDict setObject:dict forKey:keyString];
    result=[plistDict writeToFile:filePath atomically:YES];
    NSLog(@"save result=%@", result? @"success":@"fail");
    
    NSDictionary *getTestDic=[[NSDictionary alloc] initWithContentsOfFile:filePath];

这样就可以愉快的存储和读取了



(92)           获取本地APP版本号以及App Store上版本号,确定是否要升级
 NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"current Version:%@",currentVersion);
    

    NSString *url=[NSString stringWithFormat:@"%@%@",@"http://itunes.apple.com/lookup?id=",appID];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSArray *array = responseObject[@"results"];
        NSDictionary *dict = [array lastObject];
        NSString *storeVersion=[dict objectForKey:@"version"];
        NSLog(@"当前版本为:%@", dict[@"version"]);
        

        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
    }];
    
(93)            设置App多语言(国际化/本地化)
0.  首先在project-> Localization中添加你需要的语言,例如Chinese Traditional
1. 首先添加一个strings文件,名为Localizable.strings,添加方法为:add->resource->strings,命名一定要为Localizable.strings
2. 选中Localizable.strings,View->Utilities->Show File Inspector
3. 然后就可以生成相应的strings

例如Localizable.strings(English)/Localizable.strings(Chinese(Traditional))
然后在二者定义一样的Key,不一样的内容
例如
“Test”="Test"
"Test"="测试"

这样系统会根据手机的语言系统显示相应的内容

(94)            Storyboard的语言多样化
选中Storyboard,应该在以第一选项卡中找到Localization标签,
然后它会自动生成中文和英文的纯string文本,修改string的内容即可
可以参考这个文章

http://www.tuicool.com/articles/Zr67Nb2


(95)            Storyboard添加Entyy point

选中设置的ViewController,选择第四个tag,找到“Is Initial View Controller”标签选中即可
参考http://www.07net01.com/2015/07/888152.html


(96)             代码更改NavigationBar的标题

self.navigationItem.title=@"Test"即可



(97)              使用StoryBoard更改点击按钮时的背景图片
1 在Button菜单栏中的Type中将类型改为“Custom”而非默认的“System”
2. State Config为“Default”时,添加普通状态下的按钮背景图片
3. 将Statue Config的值改为“HightLighted”,然后Background中添加点击按钮时显示的背景图
4. 将Statue Config值改为“Selected”,然后Background中添加点击按钮时显示的背景图
完成~!

如果是使用代码自定义按钮不同状态下的背景图片的话,如下两行代码即可:
        [contactBookBtn setBackgroundImage:[UIImage imageNamed:@"left1.png"] forState:UIControlStateNormal];
        [contactBookBtn setBackgroundImage:[UIImage imageNamed:@"left2.png"] forState:UIControlStateSelected];


















  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值