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设置点击事件

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. -(void)initCoverView{  
  2.     coverView.userInteractionEnabled=YES;//设置该view可以交互  
  3.     UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAdvancedSearchView:)];  
  4.     [coverView addGestureRecognizer:tapGesture];  
  5. }  

下面实现方法showAdvancedSearchView:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (void)showAdvancedSearchView:(UITapGestureRecognizer *)gesture{  
  2.     NSLog(@"!!!!  click cover view");  
  3.       
  4. }  

(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 (seeLaunch 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

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #import <Foundation/Foundation.h>  
  2. #import "TNCViewController_iPhone.h"  
  3. @interface TNCViewController_iPhone ()  
  4.   
  5. @end  
  6. @implementation TNCViewController_iPhone  
  7. UIScrollView *scrollView;  
  8. UIWebView *tncWebView;  
  9. UIImageView *TNCbackgroundImageView;  
  10. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  11. {  
  12.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  13.     if (self) {  
  14.     }  
  15.     return self;  
  16. }  
  17.   
  18. - (void)viewDidLoad  
  19. {  
  20.     [super viewDidLoad];  
  21.     CGRect rx = [ UIScreen mainScreen ].bounds;  
  22.     float height=rx.size.height;  
  23.     height=self.view.bounds.size.height;  
  24.     rx.size.height=height-49-64;  
  25.     scrollView = [[UIScrollView alloc] initWithFrame:rx];  
  26.     scrollView.backgroundColor = [UIColor clearColor];  
  27.     scrollView.delegate = self;  
  28.   
  29.     [scrollView flashScrollIndicators];  
  30.     scrollView.directionalLockEnabled = YES;  
  31.       
  32.     TNCbackgroundImageView=[[UIImageView alloc]initWithFrame:rx];  
  33.     [TNCbackgroundImageView setImage:[UIImage imageNamed:@"contentBackground.png"]];  
  34.     [self.view addSubview:TNCbackgroundImageView];  
  35.       
  36.     [self.view addSubview:scrollView];  
  37.       
  38.     tncWebView=[[UIWebView alloc]initWithFrame:rx];  
  39.       
  40.     //获取文件路径  
  41.     NSString *filePath = [[NSBundle mainBundle]pathForResource:@"tnc_chi" ofType:@"html"];  
  42.     NSURL *url = [NSURL fileURLWithPath:filePath];  
  43.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  44.     [tncWebView setBackgroundColor:[UIColor clearColor]];  
  45.     [tncWebView loadRequest:request];  
  46.     tncWebView.opaque=NO;  
  47.     scrollView.contentSize=tncWebView.frame.size;  
  48.     [scrollView addSubview:tncWebView];  
  49.     [tncWebView release];  
  50.   
  51. }  
  52. @end  

(26) Label中文字居中属性

NSTextAlignmentCenter


(27) 获取连接的Wifi名称

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

2. 方法体:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSString *wifiName=nil;  
  2.     CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();  
  3.       
  4.     if (!wifiInterfaces) {  
  5.         NSLog(@"!!!!!!  No Wifi Connect");  
  6.     }  
  7.       
  8.     NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;  
  9.       
  10.     for (NSString *interfaceName in interfaces) {  
  11.         CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));  
  12.           
  13.         if (dictRef) {  
  14.             NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;  
  15.             NSLog(@"network info -> %@", networkInfo);  
  16.             wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];  
  17.               
  18.             CFRelease(dictRef);  
  19.         }  
  20.     }  
  21.       
  22.     CFRelease(wifiInterfaces);  

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

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSString *wifiName = @"Not Found";  
  2. CFArrayRef myArray = CNCopySupportedInterfaces();  
  3. if (myArray != nil) {  
  4.     CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));  
  5.     if (myDict != nil) {  
  6.         NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);  
  7.         wifiName = [dict valueForKey:@"SSID"];  
  8.     }  
  9. }  
  10. 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使用情况(动态检测开启和关闭)

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) 实现数字小时钟

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8. @synthesize timeLabel;//It's a UILabel  
  9.   
  10. NSTimer *timer;  
  11. - (void)viewDidLoad {  
  12.     [super viewDidLoad];  
  13. //    [self setTime];  
  14.     timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setTime:) userInfo:nil repeats:YES];  
  15. }  
  16.   
  17. -(void)setTime:(id)sender{  
  18.     NSDate *curtime = [NSDate date];  
  19.     NSDateFormatter *formatterCur1 = [[NSDateFormatter alloc] init];  
  20.     [formatterCur1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  
  21.     NSString *timestr1 = [formatterCur1 stringFromDate:curtime];  
  22.     timeLabel.text=timestr1;  
  23. }  
  24. - (void)didReceiveMemoryWarning {  
  25.     [super didReceiveMemoryWarning];  
  26.     // Dispose of any resources that can be recreated.  
  27. }  
  28.   
  29. //页面将要进入前台,开启定时器  
  30. -(void)viewWillAppear:(BOOL)animated  
  31. {  
  32.     //开启定时器  
  33.     [timer setFireDate:[NSDate distantPast]];  
  34. }  
  35.   
  36. //页面消失,进入后台不显示该页面,关闭定时器  
  37. -(void)viewDidDisappear:(BOOL)animated  
  38. {  
  39.     //关闭定时器  
  40.     [timer setFireDate:[NSDate distantFuture]];  
  41. }  
  42.   
  43. @end  

(37) 禁止横屏

在AppDelegate中添加:

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

{

    returnUIInterfaceOrientationMaskPortrait;

}


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

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


(39)使用现有的数据库XXX.db

1. 在Support Files文件夹内导入数据库(使用Add New Files 即可)

2.  在代码中实现:(如数据库的名字叫做Test.db)

    NSString *dbFilePath = [[NSBundlemainBundle]pathForResource:@"数据库名字,如Test"ofType:@"db"];

    NSLog(@"DB file path: %@",dbFilePath);

//    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbFilePath];

   sqlite3 *database;

   if (sqlite3_open([dbFilePathUTF8String], &database) ==SQLITE_OK)

    {

        NSLog(@"DB open success");

    }

   else {

       sqlite3_close(database);

        NSLog(@"DB open failed");

    }

这样就可以打开数据库了


(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];


(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]];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值