iOS开发入门实例

来源:互联网 发布:淘宝店升级为企业店铺 编辑:程序博客网 时间:2024/04/29 13:38


著作权声明:本文由http://blog.csdn.net/totogo2010/原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!


iOS学习之动态添加Button和监听UIAlertView按钮

1、在xib文件上拖拽添加一个button,标题为:添加button。

2、按住ctrl键拖拽到addbuttonViewController.m文件空白处,生成IBAction,填充代码后如下
点击事件后://动态创建一个新的button
- (IBAction)addButton:(id)sender {    CGRect frame = CGRectMake(90, 200, 200, 60);    UIButton *someAddButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    someAddButton.backgroundColor = [UIColor clearColor];    [someAddButton setTitle:@"动态添加一个按钮!" forState:UIControlStateNormal];    someAddButton.frame = frame;    [someAddButton addTarget:self action:@selector(someButtonClicked) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:someAddButton];}

3、动态生成的button点击事件方法:
-(void) someButtonClicked{     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"                                                    message:@"您点击了动态按钮!"                                                     delegate:self                                            cancelButtonTitle:@"确定"                                           otherButtonTitles:nil];     [alert show];}

二、监听UIAlertView。

1、在上面的代码基础上,在addbuttonViewController.h文件添加委托
#import <UIKit/UIKit.h>@interface addbuttonViewController : UIViewController<UIAlertViewDelegate>- (IBAction)addButton:(id)sender;@end

2、在AlertView中多添加两个按钮
-(void) someButtonClicked{     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"                                                    message:@"您点击了动态按钮!"                                                     delegate:self                                            cancelButtonTitle:@"确定"                                           otherButtonTitles:@"取消",@"第三项",nil];     [alert show];}

3、在对应的.m文件中实现委托中的方法

监听你点击了那个按钮
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{    NSLog(@"buttonIndex:%d", buttonIndex);}

iOS学习之iOS 使用NINetworkImageView下载图片,google地图图片的获取。

一、NINetworkImageView是Nimbus下载图片的类,类是这么描述的:

Overview

A network-enabled image view that consumes minimal amounts of memory.

Intelligently crops and resizes images for optimal memory use and uses threads to avoid processing images on the UI thread.

消耗很少的内存使用网络图片.

使用线程以避免在UI线程上下载处理,并智能,调整优化内存的使用图像。

真的很好用,一步加载图片。


首先#import "NimbusNetworkImage.h"头文件

iOS学习之Tab Bar的使用和视图切换

iOS学习之UIActionSheet的使用

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

在开发过程中,发现有时候UIActionSheet的最后一项点击失效,点最后一项的上半区域时有效,这是在特定情况下才会发生,这个场景就是试用了UITabBar的时候才有。解决办法:

在showView时这样使用,[actionSheet showInView:[UIApplication sharedApplication].keyWindow];
或者[sheet showInView:[AppDelegate sharedDelegate].tabBarController.view];这样就不会发生遮挡现象了。


iOS学习之 plist文件的读写

3 读取plist文件的数据
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];    NSLog(@"%@", data);//直接打印数据。

4、创建和写入plist文件

写入的plist文件会生成在对应程序的沙盒目录里。

<strong>- (void)viewDidLoad{    [super viewDidLoad];    //读取plist    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];    NSLog(@"%@", data);       //添加一项内容    [data setObject:@"add some content" forKey:@"c_key"];       //获取应用程序沙盒的Documents目录    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);    NSString *plistPath1 = [paths objectAtIndex:0];       //得到完整的文件名    NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"];   //输入写入    [data writeToFile:filename atomically:YES];       //那怎么证明我的数据写入了呢?读出来看看    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];    NSLog(@"%@", data1);        // Do any additional setup after loading the view, typically from a nib.}

iOS学习之Table View的简单使用

Plain:这是普通的列表风格
Grouped :这是分块风格。


iOS学习之分段Table View的使用(Grouped样式表格)

Plist文件中的数据读取出来,放到Table view里展示出来
TableView表格部分
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {    //返回省份的数组    NSMutableArray *array = [NSMutableArray arrayWithCapacity:35];    for (NSDictionary *dict in provinces) {        [array addObject:[dict objectForKey:@"p_Name"]];    }    return array;}
返回所有省份名称的数组 ,通过点击右边的省份名称能快速定位到这个省份的城市,也就是快速定位到这个section。右边的导航


iOS学习之UISwitch控件两种使用方法和监听

一、第一种创建UISwitch控件的方法,在代码中动态创建。
二、通过拖拽方法使用UISwitch


iOS学习之iOS沙盒(sandbox)机制和文件操作(一)

1、iOS沙盒机制

 iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等。

 1.1、每个应用程序都有自己的存储空间
 1.2、应用程序不能翻过自己的围墙去访问别的存储空间的内容
 1.3、应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会被放行。
     通过这张图只能从表层上理解sandbox是一种安全体系,应用程序的所有操作都要通过这个体系来执行,其中核心内容是:sandbox对应用程序执行各种操作的权限限制。





2、打开模拟器沙盒目录

下面看看模拟器的沙盒文件夹在mac电脑上的什么位置。

文件都在个人用户名文件夹下的一个隐藏文件夹里,中文叫资源库,他的目录其实是Library。

打开资源库后找到/Application Support/iPhone Simulator/文件夹。这里面就是模拟器的各个程序的沙盒目录了。

3、目录结构

默认情况下,每个沙盒含有3个文件夹:Documents, Library 和 tmp。因为应用的沙盒机制,应用只能在几个目录下读写文件
Documents:苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录
Library:存储程序的默认设置或其它状态信息;

Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除

tmp:提供一个即时创建临时文件的地方。


iOS学习之iOS沙盒(sandbox)机制和文件操作(二)

我们看看如何获取应用程序沙盒目录。包括真机的沙盒的目录。
1、获取程序的Home目录

NSString *homeDirectory = NSHomeDirectory();  
打印结果:
/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2  

2、获取document目录
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *path = [paths objectAtIndex:0];NSLog(@"path:%@", path);
打印结果:
path:/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2/Documents  

3、获取Cache目录
    
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    NSString *path = [paths objectAtIndex:0];    NSLog(@"%@", path);
打印结果:
/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2/Library/Caches  

4、获取Library目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);    NSString *path = [paths objectAtIndex:0];    NSLog(@"%@", path);
打印结果:
/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2/Library  

5、获取Tmp目录
   NSString *tmpDir = NSTemporaryDirectory();    NSLog(@"%@", tmpDir);
打印结果:
/var/folders/g7/246bh79130zblw0yjjtc55cw0000gn/T/ 

6、写入文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *docDir = [paths objectAtIndex:0];    if (!docDir) {        NSLog(@"Documents 目录未找到");           }    NSArray *array = [[NSArray alloc] initWithObjects:@"内容",@"content",nil];    NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];    [array writeToFile:filePath atomically:YES];

7、读取文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *docDir = [paths objectAtIndex:0];    NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];    NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];    NSLog(@"%@", array);

iOS学习之iOS沙盒(sandbox)机制和文件操作之NSFileManager(三)
我们看看NSFileManager如何使用。包括创建文件,目录,删除,遍历目录等。
1、在Documents里创建目录
创建一个叫test的目录,先找到Documents的目录 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);     NSString *documentsDirectory = [paths objectAtIndex:0];     NSLog(@"documentsDirectory%@",documentsDirectory);     NSFileManager *fileManager = [NSFileManager defaultManager];     NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];     // 创建目录    [fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];

2、在test目录下创建文件
 testPath 要用stringByAppendingPathComponent拼接上你要生成的文件名,比如test00.txt。这样才能在test下写入文件。

testDirectory是上面代码生成的路径哦,不要忘了。我往test文件夹里写入三个文件,test00.txt ,test22.txt,text.33.txt。内容都是写入内容,write String。

   NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];     NSString *testPath2 = [testDirectory stringByAppendingPathComponent:@"test22.txt"];     NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33   

    NSString *string = @"写入内容,write String";    [fileManager createFileAtPath:testPath contents:[string  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];    [fileManager createFileAtPath:testPath2 contents:[string  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];    [fileManager createFileAtPath:testPath3 contents:[string  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

}

在Documents目录下创建就更简单了,不用加test就ok了

3、获取目录列里所有文件名
两种方法获取:subpathsOfDirectoryAtPath 和 subpathsAtPath
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);     NSString *documentsDirectory = [paths objectAtIndex:0];     NSLog(@"documentsDirectory%@",documentsDirectory);     NSFileManager *fileManage = [NSFileManager defaultManager];     NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];     NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];    NSLog(@"%@",file);     NSArray *files = [fileManage subpathsAtPath: myDirectory ];    NSLog(@"%@",files);

获取上面刚才test文件夹里的文件名

打印结果

2012-06-17 23:23:19.684 IosSandbox[947:f803] fileList:(

    ".DS_Store",

    "test00.txt",

    "test22.txt",

    "test33.txt"

)

2012-06-17 23:23:19.686 IosSandbox[947:f803] fileLit(

    ".DS_Store",

    "test00.txt",

    "test22.txt",

    "test33.txt"

)

两个方法都可以,隐藏的文件也打印出来了。

4、fileManager使用操作当前目录
//创建文件管理器    NSFileManager *fileManager = [NSFileManager defaultManager];    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    //更改到待操作的目录下    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];    //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil    NSString * fileName = @"testFileNSFileManager.txt";    NSArray *array = [[NSArray alloc] initWithObjects:@"hello world",@"hello world1", @"hello world2",nil];    [fileManager createFileAtPath:fileName contents:array attributes:nil];

这样就创建了testFileNSFileManager.txt并把三个hello world写入文件了

changeCurrentDirectoryPath目录更改到当前操作目录时,做文件读写就很方便了,不用加上全路径

5、删除文件

接上面的代码,remove就ok了。
[fileManager removeItemAtPath:fileName error:nil]; 

6、混合数据的读写

用NSMutableData创建混合数据,然后写到文件里。并按数据的类型把数据读出来

6.1写入数据:
    NSString * fileName = @"testFileNSFileManager.txt";    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsDirectory = [paths objectAtIndex:0];    //获取文件路径    NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];    //待写入的数据    NSString *temp = @"nihao 世界";    int dataInt = 1234;    float dataFloat = 3.14f;    //创建数据缓冲    NSMutableData *writer = [[NSMutableData alloc] init];    //将字符串添加到缓冲中    [writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];      //将其他数据添加到缓冲中    [writer appendBytes:&dataInt length:sizeof(dataInt)];    [writer appendBytes:&dataFloat length:sizeof(dataFloat)];     //将缓冲的数据写入到文件中    [writer writeToFile:path atomically:YES];

我们看看数据怎么样了:


我们看到后面的是乱码,那是中文被转成了NSData后,还有int float的二进制

6.2读取刚才写入的数据:
 //读取数据:    int intData;    float floatData = 0.0;    NSString *stringData;       NSData *reader = [NSData dataWithContentsOfFile:path];    stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]                                   encoding:NSUTF8StringEncoding];    [reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))];    [reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))];    NSLog(@"stringData:%@ intData:%d floatData:%f", stringData, intData, floatData);
nihao hello! intData:1234332 floatData:3.140000

iOS学习之NSBundle介绍和使用

bundle是一个目录,其中包含了程序会使用到的资源.这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in).对应bundle,cocoa提供了类NSBundle.

我们现在用bundle获取程序里的一张图片,并显示到View上。


//    通过使用下面的方法得到程序的main bundle    NSBundle *mainBundle = [NSBundle mainBundle];       NSString *imagePath = [mainBundle pathForResource:@"QQ20120616-1" ofType:@"png"];    NSLog(@"%@", imagePath);    UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];    UIImageView  *imageView = [[UIImageView alloc] initWithImage:image];    [self.view addSubview:imageView];

/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2/iOSSandbox.app/QQ20120616-1.png

我们可以看到,图片在iOSSandbox.app这个包里,



iOS学习之UINavigationController详解与使用(一)添加UIBarButtonItem

2、UINavigationController的结构组成
UINavigationController有Navigation bar  ,Navigation View ,Navigation toobar等组成

6.在AppDelegate.m 文件的didFinishLaunchingWithOptions方法中创建添加navController,RootViewController视图
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    RootViewController *rootView = [[RootViewController alloc] init];    rootView.title = @"Root View";       self.navController = [[UINavigationController alloc] init];    [self.navController pushViewController:rootView animated:YES];    [self.window addSubview:self.navController.view];    [self.window makeKeyAndVisible];    return YES;}
现在还没有Navigation bar 。只有title。

8、添加UIBarButtonItem

bar ButtonItem分左右UIBarButtonItem。我们把左右的都添加上去。

- (void)viewDidLoad{    [super viewDidLoad];    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(selectLeftAction:)];    self.navigationItem.leftBarButtonItem = leftButton;       UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd  target:self action:@selector(selectRightAction:)];    self.navigationItem.rightBarButtonItem = rightButton;}

UIBarButtonSystemItemAction的风格,这是系统自带的按钮风格,看下图,你不用一个个试验,你也知道想用那个item,如下图:


9、响应UIBarButtonItem的事件的实现
-(void)selectLeftAction:(id)sender{    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你点击了导航栏左按钮" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];    [alter show];}-(void)selectRightAction:(id)sender{    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你点击了导航栏右按钮" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];    [alter show];}

iOS学习之UINavigationController详解与使用(二)页面切换和segmentedController

1、RootView 跳到SecondView
新建SecondView
2、为Button 添加点击事件,实现跳转
- (IBAction)gotoSecondView:(id)sender {    SecondViewController *secondView = [[SecondViewController alloc] init];    [self.navigationController pushViewController:secondView animated:YES];    secondView.title = @"Second View";}
3、添加segmentedController

在nav bar这样的效果是如何实现的呢?


这就是segmentedController。

3.1在RootViewController.m的viewDidLoad添加如下代码:
 NSArray *array = [NSArray arrayWithObjects:@"鸡翅",@"排骨", nil];    UISegmentedControl *segmentedController = [[UISegmentedControl alloc] initWithItems:array];    segmentedController.segmentedControlStyle = UISegmentedControlSegmentCenter;    [segmentedController addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];    self.navigationItem.titleView = segmentedController;
3.2[segmentedController addTarget:selfaction:的实现
-(void)segmentAction:(id)sender{    switch ([sender selectedSegmentIndex]) {        case 0:        {            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你点击了鸡翅" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];            [alter show];        }        break;    case 1:        {            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你点击了排骨" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];            [alter show];        }        break;               default:            break;    }
这样就能响应鸡翅和排骨按钮了

4、自定义backBarButtonItem

左上角的返回上级View的barButtonitem的名字是上级目录的Title,如果title或者适合做button的名字,怎么办呢?我们可以自己定义

 UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"根视图" style:UIBarButtonItemStyleDone target:nil action:nil];    self.navigationItem.backBarBuutton

6、自定义title

UINavigationController的title可以用别view替代,比如用UIButton UILable等,下面我用UIButton.

在SecondViewController.m中添加下面如下。

- (void)viewDidLoad{    [super viewDidLoad];    UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];    [button setTitle: @"自定义title" forState: UIControlStateNormal];    [button sizeToFit];    self.navigationItem.titleView = button;}
运行程序,goto secondView,运行效果




iOS学习之UINavigationController详解与使用(三)ToolBar

1、显示Toolbar 
[self.navigationController  setToolbarHidden:NO animated:YES];

2、在ToolBar上添加UIBarButtonItem
UIBarButtonItem *one = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];    UIBarButtonItem *two = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:nil action:nil];    UIBarButtonItem *three = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:nil action:nil];    UIBarButtonItem *four = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:nil action:nil];    UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];    [self setToolbarItems:[NSArray arrayWithObjects:flexItem, one, flexItem, two, flexItem, three, flexItem, four, flexItem, nil]];

3、动态添加Toolbar

UIToolbar *toolBar; 
- (void)viewDidLoad{    [super viewDidLoad];    [self.navigationController  setToolbarHidden:YES animated:YES];    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(gotoThridView:)];    toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, self.view.frame.size.height - toolBar.frame.size.height - 44.0, self.view.frame.size.width, 44.0)];    [toolBar setBarStyle:UIBarStyleDefault];    toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;    [toolBar setItems:[NSArray arrayWithObject:addButton]];    [self.view addSubview:toolBar];        // Do any additional setup after loading the view from its nib.}

iOS学习之UIDatePicker控件使用

iOS上的选择时间日期的控件:
模式,Time, Date,Date and Time  , Count Down Timer四种模式。
PickerDate控件的使用
1、新建一个Singe View Application,命名为DatePickDemo,其他设置如图
2、放置控件
3、建立xib和ViewController的关联
4、实现代码
- (IBAction)selectDate:(id)sender {    NSDate *select = [datePicker date];    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];    NSString *dateAndTime =  [dateFormatter stringFromDate:select];    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"时间提示" message:dateAndTime delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];    [alert show];}
5、修改模式成Date模式,修改代
[dateFormatter setDateFormat:@"yyyy-MM-dd"];  

 

iOS学习之WebView的使用


1、使用UIWebView加载网页

2、加载WebView


UIWebView *webView; 
- (void)viewDidLoad{    [super viewDidLoad];    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];    [self.view addSubview: webView];    [webView loadRequest:request];}

手机的网络环境是实时变化的,网络慢的时候,怎么提示用户网页正在打开呢?在网页打开出错的时候怎么提示用户呢?这时候我们就需要知道网页什么时候打开的,

什么时候加载完成,什么时候出错了。

3、实现协议,在ViewController.h修改如下:

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIWebViewDelegate>{    UIWebView *webView;}@end

UIWebView中几个重要的函数
1.- (void )webViewDidStartLoad:(UIWebView  *)webView   网页开始加载的时候调用
2.- (void )webViewDidFinishLoad:(UIWebView  *)webView  网页加载完成的时候调用
3.- (void)webView:(UIWebView *)webView  didFailLoadWithError:(NSError *)error 网页加载错误的时候调用

2012-06-23 15:20:29.728 WebViewDemo[1001:f803] webViewDidStartLoad

2012-06-23 15:20:29.991 WebViewDemo[1001:f803] webViewDidFinishLoad

那我们试试error情况,把wifi关掉,运行打印结果:

2012-06-23 15:23:58.939 WebViewDemo[1087:f803] webViewDidStartLoad

2012-06-23 15:23:59.016 WebViewDemo[1087:f803] webViewDidFinishLoad

请求结果不变,为什么关掉网络还成功了呢?缓存?
我换163.com试试,这是真正的结果出来了:

2012-06-23 15:24:41.131 WebViewDemo[1134:f803] webViewDidStartLoad

2012-06-23 15:24:41.149 WebViewDemo[1134:f803] didFailLoadWithError:Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x6b41660 {NSErrorFailingURLStringKey=http://www.163.com/, NSErrorFailingURLKey=http://www.163.com/, NSLocalizedDescription=The Internet connection appears to be offline., NSUnderlyingError=0x6eae690 "The Internet connection appears to be offline."}

连接错误了,调用了didFailLoadWithError。

5、加载等待界面

为了给用户更直观的界面效果,我们加上等待的loading界面试试

在webViewDidStartLoad加入等待
- (void) webViewDidStartLoad:(UIWebView *)webView{    //创建UIActivityIndicatorView背底半透明View        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];     [view setTag:108];     [view setBackgroundColor:[UIColor blackColor]];     [view setAlpha:0.5];     [self.view addSubview:view];        activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];     [activityIndicator setCenter:view.center];     [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];     [view addSubview:activityIndicator];     [activityIndicator startAnimating];

加载完成或失败时,去掉loading效果
- (void) webViewDidFinishLoad:(UIWebView *)webView{    [activityIndicator stopAnimating];    UIView *view = (UIView*)[self.view viewWithTag:108];    [view removeFromSuperview];    NSLog(@"webViewDidFinishLoad");}- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{    [activityIndicator stopAnimating];    UIView *view = (UIView*)[self.view viewWithTag:108];    [view removeFromSuperview];

运行效果:


iOS学习之UIPickerView控件的简单使用

UIPickerView控件在给用户选择某些特定的数据时经常使用到,这里演示一个简单的选择数据,显示在UITextField输入框里,把UIPickerView作为输入View,用Toolbar作为选定数据的按钮。和其他UITableView控件相似,UIPickerView也需要数据源。

1、新建一个Single View Application ,命名为PickerViewDemo

2、拖放控件


2.1、拖放一个UIPickerView,放置在View的最下方

2.2、拖放一个Toolbar控件,放置在View的外面,让它不属于View的子控件,并把item命名为“完成”,效果如下:

2.3 放置一个Flexible Space Bar Button Item 撑开 

2.4  放一个UITextField,用来显示选择的数据

3、创建映射

#import <UIKit/UIKit.h>@interface ViewController : UIViewController{    NSArray *pickerArray;}- (IBAction)selectButton:(id)sender;@property (strong, nonatomic) IBOutlet UIToolbar *doneToolbar;@property (strong, nonatomic) IBOutlet UIPickerView *selectPicker;@property (strong, nonatomic) IBOutlet UITextField *textField;@end

4、实现数据源和协议

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIPickerViewDelegate, UITextFieldDelegate,UIPickerViewDataSource>{    NSArray *pickerArray;}- (IBAction)selectButton:(id)sender;@property (strong, nonatomic) IBOutlet UIToolbar *doneToolbar;@property (strong, nonatomic) IBOutlet UIPickerView *selectPicker;@property (strong, nonatomic) IBOutlet UITextField *textField;@end

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{    return 1;}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{    return [pickerArray count];}

-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{    return [pickerArray objectAtIndex:row];}

-(void)textFieldDidEndEditing:(UITextField *)textField{    NSInteger row = [selectPicker selectedRowInComponent:0];    self.textField.text = [pickerArray objectAtIndex:row];}

上面numberOfComponentsInPickerView返回有几个PickerView ,

textFieldDidEndEditing这个在textField结束编辑时,显示PickerView选择中的数据。


Toolbar 的item的完成按钮
- (IBAction)selectButton:(id)sender {    [textField endEditing:YES];}

5、初始化

- (void)viewDidLoad{    [super viewDidLoad];    pickerArray = [NSArray arrayWithObjects:@"动物",@"植物",@"石头",@"天空", nil];    textField.inputView = selectPicker;    textField.inputAccessoryView = doneToolbar;    textField.delegate = self;    selectPicker.delegate = self;    selectPicker.dataSource = self;    selectPicker.frame = CGRectMake(0, 480, 320, 216);}


iOS学习之UIPickerView控件的关联选择



当选择左边的一级选项时,左边展示一级选项里含有的二级选项,选择后显示在TextField里

1、打开上篇PickerViewDemo项目

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIPickerViewDelegate, UITextFieldDelegate,UIPickerViewDataSource>{    NSArray *pickerArray;    NSArray *subPickerArray;    NSDictionary *dicPicker;}- (IBAction)selectButton:(id)sender;@property (strong, nonatomic) IBOutlet UIToolbar *doneToolbar;@property (strong, nonatomic) IBOutlet UIPickerView *selectPicker;@property (strong, nonatomic) IBOutlet UITextField *textField;@end

2、初始化

- (void)viewDidLoad{    [super viewDidLoad];    pickerArray = [NSArray arrayWithObjects:@"动物",@"植物",@"石头", nil];    dicPicker = [NSDictionary dictionaryWithObjectsAndKeys:                 [NSArray arrayWithObjects:@"鱼",@"鸟",@"虫子",            nil], @"动物",                 [NSArray arrayWithObjects:@"花",@"草",@"葵花",            nil], @"植物",                 [NSArray arrayWithObjects:@"疯狂的石头",@"花岗岩",@"鹅卵石", nil], @"石头",nil];       subPickerArray = [dicPicker objectForKey:@"动物"];    textField.inputView = selectPicker;    textField.inputAccessoryView = doneToolbar;    textField.delegate = self;    selectPicker.delegate = self;    selectPicker.dataSource = self;    selectPicker.frame = CGRectMake(0, 480, 320, 216);}

3、Component返回两个,这样就有两个齿轮了。

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{    return 2;}

4、使用宏

在#import "ViewController.h"下面定义两个宏,代表UIPickerView齿轮的左边的部分和右边的部分。左边的部分是0,右边的是1.

#import "ViewController.h"#define kFirstComponent 0#define kSubComponent 1


5、判断是那个齿轮,返回相应的数据的Count。

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{    if(component == kFirstComponent){        return [pickerArray count];    }else {        return [subPickerArray count];    }}

6、根据component返回相应的String数据

    -(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{    if(component == kFirstComponent){        return [pickerArray objectAtIndex:row];    }else {        return [subPickerArray objectAtIndex:row];    }}

7、拖动左边的齿轮时,右边的数据相应的Reload更新。

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{    if (component == kFirstComponent) {        subPickerArray = [dicPicker objectForKey:[pickerArray objectAtIndex:row]];        [pickerView selectRow:0 inComponent:kSubComponent animated:YES];        [pickerView reloadComponent:kSubComponent];    }}

8、相应选择的数据,并显示在TextField上。


-(void)textFieldDidEndEditing:(UITextField *)textField{    NSInteger firstViewRow = [selectPicker selectedRowInComponent:kFirstComponent];    NSInteger subViewRow = [selectPicker selectedRowInComponent:kSubComponent];    NSString * firstString = [pickerArray objectAtIndex:firstViewRow];    NSString * subString =  [[dicPicker objectForKey:[pickerArray objectAtIndex:firstViewRow]] objectAtIndex:subViewRow] ;    NSString *textString = [[NSString alloc ] initWithFormat:@"您选择了:%@%@%@", firstString, @" 里的 ", subString];    self.textField.text = textString;}- (IBAction)selectButton:(id)sender {    [textField endEditing:YES];}




 

iOS开发之iOS程序偏好设置(Settings Bundle)的使用

1、添加设置项

选择Single View App模版创建。项目创建完成,在项目里选择创建新文件,选择Resource 中的Settings Bundle,创建。

再给程序添加一个icon。运行



2、设置的控件

默认的生成的设置项里有这个几个控件。

分别是:Group分组,文本框,Slider,开关控件几个控件。

设置想能使用的控件如下:

设置控件类型文本框PSTextFieldSpecifier文字PSTitleValueSpecifier开关控件PSToggleSwitchSpecifierSliderPSSliderSpecifierMultivaluePSMultiValueSpecifierGroupPSGroupSpecifier子面板PSChildPaneSpecifier.

3、编辑设置项的文件


展开Settings.bundle,其中包含一个Root.plist。Settings程序中的显示项就是从Root.plist中获取的。单击Root.plist以打开它,在空白处单击,选中Show Raw Keys/Values:

我们把原有的项删掉,添加自己的设置项,添加如下:


4、在程序中获取Settings 和写入Settings 添加UI


5、实现读取设置和保存代码

 

在两个Button的按下事件实现如下:

- (IBAction)getSettings:(id)sender {    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    username.text =  [defaults objectForKey:@"username"];    selectedAihao = [defaults objectForKey:@"aihao"];    NSLog(@"aihao:%@",selectedAihao);    NSInteger aihaoIndex = [aihaoValues indexOfObject:selectedAihao];    [pickerView selectRow:aihaoIndex inComponent:0 animated:YES];    [level setValue:[defaults integerForKey:@"levelState"]];}- (IBAction)setSettings:(id)sender {    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    [defaults setValue:username.text forKey:@"username"];    NSInteger aihaoIndex = [aihaoTitles indexOfObject:selectedAihao];    [defaults setValue:[aihaoValues  objectAtIndex:aihaoIndex] forKey:@"aihao"];    [defaults setInteger:level.value forKey:@"levelState"];    UIAlertView *alert = [[UIAlertView alloc]                                initWithTitle:@"偏好设置"                                message:@"偏好设置已经保存!"                                delegate:nil                                cancelButtonTitle: @"完成"                                otherButtonTitles:nil];     [alert show];}

头文件实现:
#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>{    NSMutableArray *aihaoTitles;    NSMutableArray *aihaoValues;    NSString *selectedAihao;}@property (strong, nonatomic) IBOutlet UITextField *username;@property (strong, nonatomic) IBOutlet UIPickerView *pickerView;@property (strong, nonatomic) IBOutlet UISlider *level;- (IBAction)getSettings:(id)sender;- (IBAction)setSettings:(id)sender;- (IBAction)doneEdit:(id)sender;@end


.m文件中其他代码:
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize username;@synthesize pickerView;@synthesize level;- (void)viewDidLoad{    [super viewDidLoad];    aihaoTitles = [[NSMutableArray alloc] init];    [aihaoTitles addObject:@"足球"];    [aihaoTitles addObject:@"篮球"];    [aihaoTitles addObject:@"乒乓球"];    aihaoValues = [[NSMutableArray alloc] init];    [aihaoValues addObject:@"football"];    [aihaoValues addObject:@"basketball"];    [aihaoValues addObject:@"pingpong"];     // Do any additional setup after loading the view, typically from a nib.}- (void)viewDidUnload{    [self setUsername:nil];    [self setPickerView:nil];    [self setLevel:nil];    [super viewDidUnload];    // Release any retained subviews of the main view.}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{     return 1;}-(NSInteger) pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component{     return [aihaoTitles count];}-(NSString *) pickerView:(UIPickerView *)pickerView               titleForRow:(NSInteger)row               forComponent:(NSInteger)component{     return [aihaoTitles objectAtIndex:row];}-(void) pickerView:(UIPickerView *)pickerView       didSelectRow:(NSInteger)row        inComponent:(NSInteger)component{     selectedAihao = [aihaoTitles objectAtIndex:row];}- (IBAction)doneEdit:(id)sender{   }

运行,输入姓名zhongguo 和爱好 足球,选择等级,保存设置。打开设置查看,可以读取到保存后的设置。



 

iOS学习之UITableView中Cell的操作

这里主要讲UITableView 中的Cell的操作,包括标记、移动、删除、插入。
NSArray *list -》NSMutableArray *list 

1、标记Cell。

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{//    NSString *rowString = [self.list objectAtIndex:[indexPath row]];//    UIAlertView * alter = [[UIAlertView alloc] initWithTitle:@"选中的行信息" message:rowString delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];//    [alter show];    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];    if (cell.accessoryType == UITableViewCellAccessoryNone) {        cell.accessoryType = UITableViewCellAccessoryCheckmark;    }else {        cell.accessoryType = UITableViewCellAccessoryNone;    }    [tableView deselectRowAtIndexPath:indexPath animated:YES];}

标记分别有四种效果:

UITableViewCellAccessoryCheckmark
UITableViewCellAccessoryDetailDisclosureButton
UITableViewCellAccessoryDisclosureIndicator
UITableViewCellAccessoryNone

2、删除Cell


在viewDidload里添加

    [self.tableViewsetEditing:YES];

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {    NSUInteger row = [indexPath row];    if (editingStyle == UITableViewCellEditingStyleDelete) {        [self.list removeObjectAtIndex:row];        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]                         withRowAnimation:UITableViewRowAnimationAutomatic];    }}

这个方法根据参数editingStyle是UITableViewCellEditingStyleDelete

在这删除行的方法又出现了一个常量:UITableViewRowAnimationAutomatic,它表示删除时的效果,类似的常量还有:
UITableViewRowAnimationAutomatic
UITableViewRowAnimationTop
UITableViewRowAnimationBottom
UITableViewRowAnimationLeft
UITableViewRowAnimationRight
UITableViewRowAnimationMiddle
UITableViewRowAnimationFade
UITableViewRowAnimationNone


3、移动Cell

3.1先把默认的删除的图标去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {    return UITableViewCellEditingStyleInsert;} 
3.2返回当前Cell是否可以移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {    return YES;}
3.3执行移动操作
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {    NSUInteger fromRow = [sourceIndexPath row];    NSUInteger toRow = [destinationIndexPath row];       id object = [self.list objectAtIndex:fromRow];    [self.list removeObjectAtIndex:fromRow];    [self.list insertObject:object atIndex:toRow];}


4、插入cell:

4.1插入和删除差不多,在

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath添加UITableViewCellEditingStyleInsert判断- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {    NSUInteger row = [indexPath row];    if (editingStyle == UITableViewCellEditingStyleDelete) {        [self.list removeObjectAtIndex:row];        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]                         withRowAnimation:UITableViewRowAnimationAutomatic];    }else if(editingStyle == UITableViewCellEditingStyleInsert ){        NSArray *insertIndexPaths = [NSArray arrayWithObjects:indexPath,nil];        [self.list insertObject:@"inset new Cell" atIndex:row];        [tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationMiddle];    }}

4.2 修改图标为插入样式。
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {    return UITableViewCellEditingStyleInsert;}
运行,点加号图标,



iOS学习之Map,定位,标记位置的使用
 
有标注(大头针),定位,地图。

1、添加地图

1.1 新一个Single View app ,选择默认项,创建后,在ViewController.h 
#import <UIKit/UIKit.h>#import <MapKit/MapKit.h>#import <CoreLocation/CoreLocation.h>@interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> {    MKMapView *map;    CLLocationManager *locationManager;}@end

1.2在ViewController.m中添加
- (void)viewDidLoad{    map = [[MKMapView alloc] initWithFrame:[self.view bounds]];     map.showsUserLocation = YES;     map.mapType = MKMapTypeSatellite;    [self.view addSubview:map];    [super viewDidLoad];     // Do any additional setup after loading the view, typically from a nib.}

这里map.mapType =MKMapTypeSatellite;我用到是卫星地图,可以使用标准的地图,

map.mapType =MKMapTypeStandard;


2、定位到指定经纬度

CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(39.915352,116.397105);          float zoomLevel = 0.02;     MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));     [map setRegion:[map regionThatFits:region] animated:YES];<span style="font-family: Tahoma; line-height: 26px; background-color: rgb(255, 255, 255);">  </span>

3、添加标注大头针

 3.1 新建一个标注类:CustomAnnotation
#import <Foundation/Foundation.h>#import <MapKit/MapKit.h>@interface CustomAnnotation : NSObject <MKAnnotation>{     CLLocationCoordinate2D coordinate;     NSString *title;     NSString *subtitle;}-(id) initWithCoordinate:(CLLocationCoordinate2D) coords;@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;@property (nonatomic, retain) NSString *title;@property (nonatomic, retain) NSString *subtitle;@end

#import "CustomAnnotation.h"@implementation CustomAnnotation@synthesize coordinate, title, subtitle;-(id) initWithCoordinate:(CLLocationCoordinate2D) coords{     if (self = [super init]) {          coordinate = coords;     }     return self;}@end
3.1 使用大头针,
-(void)createAnnotationWithCoords:(CLLocationCoordinate2D) coords {     CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:                                              coords];     annotation.title = @"标题";     annotation.subtitle = @"子标题";     [map addAnnotation:annotation];}
调用
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(39.915352,116.397105);          float zoomLevel = 0.02;     MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));     [map setRegion:[map regionThatFits:region] animated:YES];          [self createAnnotationWithCoords:coords];

4、定位到当前位置并获取当前经纬度

前面我们已经添加了locationManager,现在在DidViewLoad里直接调用

locationManager = [[CLLocationManager alloc] init];    locationManager.delegate = self;    [locationManager startUpdatingLocation];

实现协议方法收到定位成功后的经纬度
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {    [locationManager stopUpdatingLocation];        NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);}- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {    NSLog(@"locError:%@", error);}

定位后,移动到当前位置
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {    [locationManager stopUpdatingLocation];        NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);        CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(newLocation.coordinate.latitude,newLocation.coordinate.longitude);     float zoomLevel = 0.02;     MKCoordinateRegion region = MKCoordinateRegionMake(coords,MKCoordinateSpanMake(zoomLevel, zoomLevel));     [map setRegion:[map regionThatFits:region] animated:YES];}

5、会遇到的问题:

运行是发现了编译错误:

Undefined symbols for architecture i386:

  "_CLLocationCoordinate2DMake", referenced from:

      -[ViewController viewDidLoad] in ViewController.o

      -[ViewController locationManager:didUpdateToLocation:fromLocation:] in ViewController.o

  "_OBJC_CLASS_$_MKMapView", referenced from:

      objc-class-ref in ViewController.o

  "_OBJC_CLASS_$_CLLocationManager", referenced from:

      objc-class-ref in ViewController.o

ld: symbol(s) not found for architecture i386

clang: error: linker command failed with exit code 1 (use -v to see invocation)

这是为什么呢?没有添加对应的FrameWork。

 

iOS学习之sqlite的创建数据库,表,插入查看数据

iOS sqlite数据库操作。步骤是:

先加入sqlite开发库libsqlite3.dylib,

新建或打开数据库,

创建数据表,

插入数据,

查询数据并打印

1、新建项目sqliteDemo,添加使用sqlite的库libsqlite3.dylib


2、sqlite 的方法

sqlite3          *db, 数据库句柄,跟文件句柄FILE很类似

sqlite3_stmt      *stmt, 这个相当于ODBC的Command对象,用于保存编译好的SQL语句
sqlite3_open(),   打开数据库,没有数据库时创建。
sqlite3_exec(),   执行非查询的sql语句
Sqlite3_step(), 在调用sqlite3_prepare后,使用这个函数在记录集中移动。
Sqlite3_close(), 关闭数据库文件
还有一系列的函数,用于从记录集字段中获取数据,如
sqlite3_column_text(), 取text类型的数据。
sqlite3_column_blob(),取blob类型的数据
sqlite3_column_int(), 取int类型的数据

3、获取沙盒目录,并创建或打开数据库。

viewController.h头文件添加一个成员变量,并包含头文件sqlite3.h

#import <UIKit/UIKit.h>#import <sqlite3.h>@interface ViewController : UIViewController{    sqlite3 *db;}@end

在.m文件 定义宏,方面后面使用
#define DBNAME    @"personinfo.sqlite"#define NAME      @"name"#define AGE       @"age"#define ADDRESS   @"address"#define TABLENAME @"PERSONINFO"   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documents = [paths objectAtIndex:0];    NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];        if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) {        sqlite3_close(db);        NSLog(@"数据库打开失败");    }
sqlite3_open,如果数据不存在,则创建。运行。这是在沙盒目录下能看到数据库文件

4、创建数据表

创建一个独立的执行sql语句的方法,传入sql语句,就执行sql语句

-(void)execSql:(NSString *)sql{    char *err;    if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {        sqlite3_close(db);        NSLog(@"数据库操作数据失败!");    }}

创建数据表PERSONINFO的语句
NSString *sqlCreateTable = @"CREATE TABLE IF NOT EXISTS PERSONINFO (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT)";
    [self execSql:sqlCreateTable];

5、插入数据:

NSString *sql1 = [NSString stringWithFormat:                         @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",                         TABLENAME, NAME, AGE, ADDRESS, @"张三", @"23", @"西城区"];        NSString *sql2 = [NSString stringWithFormat:                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",                      TABLENAME, NAME, AGE, ADDRESS, @"老六", @"20", @"东城区"];    [self execSql:sql1];    [self execSql:sql2];

6、查询数据库并打印数据

 NSString *sqlQuery = @"SELECT * FROM PERSONINFO";    sqlite3_stmt * statement;        if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {        while (sqlite3_step(statement) == SQLITE_ROW) {            char *name = (char*)sqlite3_column_text(statement, 1);            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];                        int age = sqlite3_column_int(statement, 2);                        char *address = (char*)sqlite3_column_text(statement, 3);            NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];                        NSLog(@"name:%@  age:%d  address:%@",nsNameStr,age, nsAddressStr);        }    }    sqlite3_close(db);
2012-06-29 13:25:32.205 sqlitDemo[3587:f803] name:张三  age:23  address:西城区
2012-06-29 13:25:32.206 sqlitDemo[3587:f803] name:老六  age:20  address:东城区

最后关闭数据库。

iOS自定义的UISwitch按钮
自定义的Switch按钮

#import <Foundation/Foundation.h>@interface HMCustomSwitch : UISlider {     BOOL on;     UIColor *tintColor;     UIView *clippingView;     UILabel *rightLabel;     UILabel *leftLabel;          // private member     BOOL m_touchedSelf;}@property(nonatomic,getter=isOn) BOOL on;@property (nonatomic,retain) UIColor *tintColor;@property (nonatomic,retain) UIView *clippingView;@property (nonatomic,retain) UILabel *rightLabel;@property (nonatomic,retain) UILabel *leftLabel;+ (HMCustomSwitch *) switchWithLeftText: (NSString *) tag1 andRight: (NSString *) tag2;- (void)setOn:(BOOL)on animated:(BOOL)animated;

#import "HMCustomSwitch.h"@implementation HMCustomSwitch@synthesize on;@synthesize tintColor, clippingView, leftLabel, rightLabel;+(HMCustomSwitch *)switchWithLeftText:(NSString *)leftText andRight:(NSString *)rightText{     HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];          switchView.leftLabel.text = leftText;     switchView.rightLabel.text = rightText;          return [switchView autorelease];}-(id)initWithFrame:(CGRect)rect{     if ((self=[super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y,95,27)]))     {          //          self.clipsToBounds = YES;                    [self awakeFromNib];          // do all setup in awakeFromNib so that control can be created manually or in a nib file     }     return self;}-(void)awakeFromNib{     [super awakeFromNib];          self.backgroundColor = [UIColor clearColor];     [self setThumbImage:[UIImage imageNamed:@"switchThumb.png"] forState:UIControlStateNormal];     [self setMinimumTrackImage:[UIImage imageNamed:@"switchBlueBg.png"] forState:UIControlStateNormal];     [self setMaximumTrackImage:[UIImage imageNamed:@"switchOffPlain.png"] forState:UIControlStateNormal];          self.minimumValue = 0;     self.maximumValue = 1;     self.continuous = NO;          self.on = NO;     self.value = 0.0;          self.clippingView = [[UIView alloc] initWithFrame:CGRectMake(4,2,87,23)];     self.clippingView.clipsToBounds = YES;     self.clippingView.userInteractionEnabled = NO;     self.clippingView.backgroundColor = [UIColor clearColor];     [self addSubview:self.clippingView];     [self.clippingView release];          NSString *leftLabelText = NSLocalizedString(@"ON","Custom UISwitch ON label. If localized to empty string then I/O will be used");     if ([leftLabelText length] == 0)          {          leftLabelText = @"l";          // use helvetica lowercase L to be a 1.      }          self.leftLabel = [[UILabel alloc] init];     self.leftLabel.frame = CGRectMake(0, 0, 48, 23);     self.leftLabel.text = leftLabelText;     self.leftLabel.textAlignment = NSTextAlignmentCenter;     self.leftLabel.font = [UIFont boldSystemFontOfSize:17];     self.leftLabel.textColor = [UIColor whiteColor];     self.leftLabel.backgroundColor = [UIColor clearColor];     //          self.leftLabel.shadowColor = [UIColor redColor];     //          self.leftLabel.shadowOffset = CGSizeMake(0,0);     [self.clippingView addSubview:self.leftLabel];     [self.leftLabel release];               NSString *rightLabelText = NSLocalizedString(@"OFF","Custom UISwitch OFF label. If localized to empty string then I/O will be used");     if ([rightLabelText length] == 0)          {          rightLabelText = @"O";     // use helvetica uppercase o to be a 0.      }          self.rightLabel = [[UILabel alloc] init];     self.rightLabel.frame = CGRectMake(95, 0, 48, 23);     self.rightLabel.text = rightLabelText;     self.rightLabel.textAlignment = NSTextAlignmentCenter;     self.rightLabel.font = [UIFont boldSystemFontOfSize:17];     self.rightLabel.textColor = [UIColor grayColor];     self.rightLabel.backgroundColor = [UIColor clearColor];     //          self.rightLabel.shadowColor = [UIColor redColor];     //          self.rightLabel.shadowOffset = CGSizeMake(0,0);     [self.clippingView addSubview:self.rightLabel];     [self.rightLabel release];          }-(void)layoutSubviews{     [super layoutSubviews];          //     NSLog(@"leftLabel=%@",NSStringFromCGRect(self.leftLabel.frame));          // move the labels to the front     [self.clippingView removeFromSuperview];     [self addSubview:self.clippingView];          CGFloat thumbWidth = self.currentThumbImage.size.width;     CGFloat switchWidth = self.bounds.size.width;     CGFloat labelWidth = switchWidth - thumbWidth;     CGFloat inset = self.clippingView.frame.origin.x;          //     NSInteger xPos = self.value * (self.bounds.size.width - thumbWidth) - (self.leftLabel.frame.size.width - thumbWidth/2);      NSInteger xPos = self.value * labelWidth - labelWidth - inset;     self.leftLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);          //     xPos = self.value * (self.bounds.size.width - thumbWidth) + (self.rightLabel.frame.size.width - thumbWidth/2);      xPos = switchWidth + (self.value * labelWidth - labelWidth) - inset;      self.rightLabel.frame = CGRectMake(xPos, 0, labelWidth, 23);          //     NSLog(@"value=%f    xPos=%i",self.value,xPos);     //     NSLog(@"thumbWidth=%f    self.bounds.size.width=%f",thumbWidth,self.bounds.size.width);}- (UIImage *)image:(UIImage*)image tintedWithColor:(UIColor *)tint {              if (tint != nil)      {          UIGraphicsBeginImageContext(image.size);                    //draw mask so the alpha is respected          CGContextRef currentContext = UIGraphicsGetCurrentContext();          CGImageRef maskImage = [image CGImage];          CGContextClipToMask(currentContext, CGRectMake(0, 0, image.size.width, image.size.height), maskImage);          CGContextDrawImage(currentContext, CGRectMake(0,0, image.size.width, image.size.height), image.CGImage);                    [image drawAtPoint:CGPointMake(0,0)];          [tint setFill];          UIRectFillUsingBlendMode(CGRectMake(0,0,image.size.width,image.size.height),kCGBlendModeColor);          UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();          UIGraphicsEndImageContext();                  return newImage;    }    else      {        return image;    }}-(void)setTintColor:(UIColor*)color{     if (color != tintColor)     {          [tintColor release];          tintColor = [color retain];                    [self setMinimumTrackImage:[self image:[UIImage imageNamed:@"switchBlueBg.png"] tintedWithColor:tintColor] forState:UIControlStateNormal];     }     }- (void)setOn:(BOOL)turnOn animated:(BOOL)animated;{     on = turnOn;          if (animated)     {          [UIView     beginAnimations:nil context:nil];          [UIView setAnimationDuration:0.2];     }          if (on)     {          self.value = 1.0;     }     else      {          self.value = 0.0;     }          if (animated)     {          [UIView     commitAnimations];          }}- (void)setOn:(BOOL)turnOn{     [self setOn:turnOn animated:NO];}- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{     NSLog(@"preendTrackingWithtouch");     [super endTrackingWithTouch:touch withEvent:event];     NSLog(@"postendTrackingWithtouch");     m_touchedSelf = YES;          [self setOn:on animated:YES];}- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{     [super touchesBegan:touches withEvent:event];          NSLog(@"touchesBegan");     m_touchedSelf = NO;     on = !on;}- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{     [super touchesEnded:touches withEvent:event];     NSLog(@"touchesEnded");          if (!m_touchedSelf)     {          [self setOn:on animated:YES];          [self sendActionsForControlEvents:UIControlEventValueChanged];     }}-(void)dealloc{     [tintColor release];     [clippingView release];     [rightLabel release];     [leftLabel release];          [super dealloc];}@end
看代码可以知道,其实它是通过继承UISlider控件实现的,UISlider的左右分别是个UILabel,当YES的时候,滑块滑到了最右边,NO的时候滑到了最左边。

如何在代码中使用它呢?很简单:

- (void)loadView{     UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];     self.view = contentView;     contentView.backgroundColor = [UIColor whiteColor];          // Standard ON/OFF     HMCustomSwitch *switchView = [[HMCustomSwitch alloc] initWithFrame:CGRectZero];     switchView.center = CGPointMake(160.0f, 20.0f);     switchView.on = YES;     [contentView addSubview:switchView];     [switchView release];          // Custom YES/NO     switchView = [HMCustomSwitch switchWithLeftText:@"YES" andRight:@"NO"];     switchView.center = CGPointMake(160.0f, 60.0f);     switchView.on = YES;     [contentView addSubview:switchView];          // Custom font and color     switchView = [HMCustomSwitch switchWithLeftText:@"Hello " andRight:@"ABC "];     switchView.center = CGPointMake(160.0f, 100.0f);     switchView.on = YES;     [switchView.leftLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];     [switchView.rightLabel setFont:[UIFont italicSystemFontOfSize:15.0f]];     [switchView.rightLabel setTextColor:[UIColor blueColor]];     [contentView addSubview:switchView];          // Multiple lines     switchView = [HMCustomSwitch switchWithLeftText:@"Hello\nWorld" andRight:@"Bye\nWorld"];     switchView.center = CGPointMake(160.0f, 140.0f);     switchView.on = YES;     switchView.tintColor = [UIColor orangeColor];     switchView.leftLabel.font = [UIFont boldSystemFontOfSize:9.0f];     switchView.rightLabel.font = [UIFont boldSystemFontOfSize:9.0f];     switchView.leftLabel.numberOfLines = 2;     switchView.rightLabel.numberOfLines = 2;     switchView.leftLabel.lineBreakMode = NSLineBreakByWordWrapping;     switchView.rightLabel.lineBreakMode = NSLineBreakByWordWrapping;     [contentView addSubview:switchView];          switchView = [[HMCustomSwitch alloc] init];     switchView.center = CGPointMake(160.0f, 180.0f);     switchView.on = YES;     switchView.tintColor = [UIColor purpleColor];     [contentView addSubview:switchView];     [switchView release];          switchView = [HMCustomSwitch switchWithLeftText:@"l" andRight:@"O"];     switchView.center = CGPointMake(160.0f, 220.0f);//     customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];//     customSwitch.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];     [contentView addSubview:switchView];     // Standard ON/OFF     switchView = [[HMCustomSwitch alloc] init];     switchView.center = CGPointMake(160.0f, 260.0f);     switchView.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];     [switchView addTarget:self action:@selector(switchFlipped:) forControlEvents:UIControlEventValueChanged];     [contentView addSubview:switchView];     [switchView release];                    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];     toolbar.tintColor = [UIColor colorWithRed:125.f/255.f green:157.f/255.f blue:93.f/255.f alpha:1.0];     [contentView addSubview:toolbar];          [contentView release];}-(void)switchFlipped:(HMCustomSwitch*)switchView{     NSLog(@"switchFlipped=%f  on:%@",switchView.value, (switchView.on?@"Y":@"N"));     }

0 0
原创粉丝点击