|

楼主 |
发表于 2012-12-4 23:08:52
|
显示全部楼层
当程序中含有多个view,需要在之间切换的时候,可以使用UINavigationController,或者是ModalViewController。UINabigationController 是通过向导条来切换多个view。而如果view 的数量比较少,且显示领域为全屏的时候,用ModalViewController 就比较合适(比如需要用户输入信息的view,结束后自动回复到之前的view)。今天我们就看看ModalViewController 的创建方法。
ModalViewController 并不像UINavigationController 是一个专门的类,使用UIViewController 的presentModalViewController 方法指定之后就是ModalViewController 了。
这里使用上两回做成的CustomViewController(由UIViewController继承)来实现ModalViewController 的实例。
首先,准备ModalViewController 退出时的函数。调用UIViewController 的dismissModalViewController:Animated: 方法就可以了,如下所示:
// 这里按钮按下的时候退出ModalViewController
-(void)dismiss:(id)inSender {
// 如果是被presentModalViewController 以外的实例调用,parentViewController 将是nil,下面的调用无效
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
接下来,生成另一个CustomViewController 的实例,用来表示ModalViewController,并将其对应的view 设置成红色。然后传递给presentModalViewController: Animated: 显示ModalViewController 的view。
- (void)applicationDidFinishLaunching:(UIApplication *)application {
controller = [[CustomViewController alloc] init];
[window addSubview:controller.view];
[window makeKeyAndVisible];
// 生成ModalViewController
CustomViewController* controllerB = [[CustomViewController alloc] init];
// 设置view 的背景为红色
controllerB.view.backgroundColor = [UIColor redColor];
// 显示ModalViewController view
[controller presentModalViewController:controllerB animated:YES];
// presentModalViewController 已经被controller 管理,这里可以释放该实例了
[controllerB release];
}
编译执行以后,首先启动的是红色背景的ModalViewController view、按下按钮后恢复到蓝色背景的通常view 上。
也可以在显示ModalViewController view 之前设置UIViewContrller 的modalTransitionStyle 属性,使其以动画形式显示。
1
controllerB.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
以上的实现只是单一地实现了ModalViewController view 的功能,除了程序开始提醒用户一些信息外什么也做不了。另外由于是放入了applicationDidFinishLaunching 中的原因,也不能反复的显示。另外,在ModalViewController view 上设置的内容也不能反映到原来的view 上。
接下来我们将实现这些功能。
首先,从ModalViewController view 退出的时候,需要通知原先的view。这里使用iPhone/Cocoa 应用程序中经常使用的Delegate 设计模式(也是推荐使用的)。
实际上,系统所提供的图像选择控制类UIImagePickerController
或者是参照地址簿时的ABPeoplePickerNavigationController 类,都用到了Delegate 模式。
基于上一讲的中的例子,这里我们追加为3个按钮,分别是绿色,灰色和取消。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blueColor];
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100,100,100,100);
button.tag = 1;
[button setTitle:@"绿色" forState:UIControlStateNormal];
// 按钮事件对应函数
[button addTarget:self action:@selector(dismiss:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100,200,100,100);
button.tag = 2;
[button setTitle:@"灰色" forState:UIControlStateNormal];
// 按钮事件对应函数
[button addTarget:self action:@selector(dismiss:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100,300,100,100);
button.tag = 0;
[button setTitle:@"取消" forState:UIControlStateNormal];
// 按钮事件对应函数
[button addTarget:self action:@selector(dismiss:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
程序启动的时候依然是先显示ModalViewController view,按下任何一个按钮,将关闭该view。按下“绿色”按钮,设置背景为绿色,按下“灰色”按钮时,设置背景为灰色。“取消”的时候什么也不做。
委托处理用下面的函数实现,当参数inColor 为nil 的时候代表取消。
-(void)selectColor:(UIColor*)inColor;
委托代理的实例用id 变量表示。
@interface CustomViewController : UIViewController {
id colorSelectDelegate;
}
设置该变量的函数如下。
-(void)setColorSelectDelegate:(id)inDelegate {
colorSelectDelegate = inDelegate;
}
另外如上面viewDidLoad 所示,按钮的tag 分别为0、1、2。按钮按下时调用的函数中由不同的tag 来发送不同的UIColor实例到colorSelectDelegate 上。
-(void)dismiss:(id)inSender {
UIView* view = (UIView*)inSender;
UIColor* requestColor = nil;
if (view.tag == 1)
requestColor = [UIColor greenColor];
if (view.tag == 2)
requestColor = [UIColor grayColor];
[colorSelectDelegate selectColor:requestColor];
}
这是不使用UIButton* 而是用UIView* ,是因为tag 属性被定义在UIView 类中,不需要必须转换为UIButton 类。
另外这样一来,该函数在UIButton 以外的情况下也能被使用。
如果想检查id 是什么类性的可以使用isKindOfClass: 方法。
接收到具体的参数inColor 更换背景色,并关闭ModalViewController view。
-(void)selectColor:(UIColor*)inColor {
if (inColor != nil)
self.view.backgroundColor = inColor;
[self dismissModalViewControllerAnimated:YES];
}
另外,在调用presentModalViewController 之前(显示ModalViewController view 之前),需要设定委托的实例。
- (void)applicationDidFinishLaunching:(UIApplication *)application {
controller = [[CustomViewController alloc] init];
[window addSubview:controller.view];
[window makeKeyAndVisible];
// 创建ModalViewController view 的Controller
CustomViewController* controllerB = [[CustomViewController alloc] init];
// 设置背景色为红色
controllerB.view.backgroundColor = [UIColor redColor];
// 设置委托实例
[controllerB setColorSelectDelegate:controller];
// 显示ModalViewController view
[controller presentModalViewController:controllerB animated:YES];
[controllerB release];
}
编译一下,程序启动后显示红色背景的ModalViewController view,点击绿色按钮后,原先的view的背景变为绿色,点击灰色,显示灰色的背景,而点击取消,那么将显示原先蓝色的背景。
这样的形式,就是将按钮的动作委托给原先view的Controller 来处理了。根据送来的UIColor 来设置不同的背景色。
这一回来定制UIView 上的触摸事件,作为例子,只是简单地检测出触摸事件并显示当前坐标在控制台上。
首先添加新文件,如下图:
在显示的对话框中选中Cocoa Touch Class 的Objective C class ⇒UIView
在项目的添加菜单中选择Touch 。检测触摸时间需要实现下面的函数。
- (void)touchesBegan:(NSSet *)touches
withEvent:(UIEvent *)event;
这个函数由用户触摸屏幕以后立刻被调到。为了自定义他的行为,我们像下面来实现:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint pt = [touch locationInView:self];
printf("point = %lf,%lf\n", pt.x, pt.y);
}
上面的代码将触摸点的坐标取出,并打印到控制台上。
如果需要得到多点触摸(不只是一根手指)的信息,需要使用anyObject 实例指定UIView。
另外,TouchAppDelegate 的applicationDidFinishLaunching 函数像下面一样实现:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
TouchView* view = [[TouchView alloc]
initWithFrame:CGRectMake(100, 100, 200, 200)];
view.backgroundColor = [UIColor greenColor];
[window addSubview:view];
[window makeKeyAndVisible];
[view release];
}
这里用intiWithFrame 指定的矩形区域可以任意。另外为了明确触摸的区域大小,设定其view.backgroundColor。
虽然通过initWithFrame 在TouchAppDelegate 内创建了TouchView 的实例、但是通过addSubview:view 将管理责任交给了window 。就是说,TouchAppDelegate 与window 两个实例都对TouchView 实例实施管理。所以这里用[view release] 释放TouchAppDelegate 的管理责任
今天我们来看看iPhone 中数据库的使用方法。iPhone 中使用名为SQLite 的数据库管理系统。它是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。
其使用步骤大致分为以下几步:
创建DB文件和表格
添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)
通过FMDB 的方法使用SQLite
创建DB文件和表格
$ sqlite3 sample.db
sqlite> CREATE TABLE TEST(
...> id INTEGER PRIMARY KEY,
...> name VARCHAR(255)
...> );
简单地使用上面的语句生成数据库文件后,用一个图形化SQLite管理工具,比如Lita 来管理还是很方便的。
然后将文件(sample.db)添加到工程中。
添加必须的库文件(FMDB for iPhone, libsqlite3.0.dylib)
首先添加Apple 提供的sqlite 操作用程序库ibsqlite3.0.dylib 到工程中。
位置如下
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS${VER}.sdk/usr/lib/libsqlite3.0.dylib
这样一来就可以访问数据库了,但是为了更加方便的操作数据库,这里使用FMDB for iPhone。
svn co http://flycode.googlecode.com/svn/trunk/fmdb fmdb
如上下载该库,并将以下文件添加到工程文件中:
FMDatabase.h
FMDatabase.m
FMDatabaseAdditions.h
FMDatabaseAdditions.m
FMResultSet.h
FMResultSet.m
通过FMDB 的方法使用SQLite
使用SQL 操作数据库的代码在程序库的fmdb.m 文件中大部分都列出了、只是连接数据库文件的时候需要注意 — 执行的时候,参照的数据库路径位于Document 目录下,之前把刚才的sample.db 文件拷贝过去就好了。
位置如下
/Users/xxxx/Library/Application Support/iPhone Simulator/User/Applications/xxxx/Documents/sample.db
以下为链接数据库时的代码:
BOOL success;
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fm fileExistsAtPath:writableDBPath];
if(!success){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
}
// 连接DB
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
if ([db open]) {
[db setShouldCacheStatements:YES];
// INSERT
[db beginTransaction];
int i = 0;
while (i++ < 20) {
[db executeUpdate:@"INSERT INTO TEST (name) values (?)" , [NSString stringWithFormat:@"number %d", i]];
if ([db hadError]) {
NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
}
}
[db commit];
// SELECT
FMResultSet *rs = [db executeQuery:@"SELECT * FROM TEST"];
while ([rs next]) {
NSLog(@"%d %@", [rs intForColumn:@"id"], [rs stringForColumn:@"name"]);
}
[rs close];
[db close];
}else{
NSLog(@"Could not open db.");
}
接下来再看看用DAO 的形式来访问数据库的使用方法,代码整体构造如下。

首先创建如下格式的数据库文件:
$ sqlite3 sample.db
sqlite> CREATE TABLE TbNote(
...> id INTEGER PRIMARY KEY,
...> title VARCHAR(255),
...> body VARCHAR(255)
...> );
创建DTO(Data Transfer Object)
//TbNote.h
#import <Foundation/Foundation.h>
@interface TbNote : NSObject {
int index;
NSString *title;
NSString *body;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *body;
- (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody;
- (int)getIndex;
@end
//TbNote.m
#import "TbNote.h"
@implementation TbNote
@synthesize title, body;
- (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{
if(self = [super init]){
index = newIndex;
self.title = newTitle;
self.body = newBody;
}
return self;
}
- (int)getIndex{
return index;
}
- (void)dealloc {
[title release];
[body release];
[super dealloc];
}
@end
创建DAO(Data Access Objects)
这里将FMDB 的函数调用封装为DAO 的方式。
//BaseDao.h
#import <Foundation/Foundation.h>
@class FMDatabase;
@interface BaseDao : NSObject {
FMDatabase *db;
}
@property (nonatomic, retain) FMDatabase *db;
-(NSString *)setTable:(NSString *)sql;
@end
//BaseDao.m
#import "SqlSampleAppDelegate.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "BaseDao.h"
@implementation BaseDao
@synthesize db;
- (id)init{
if(self = [super init]){
// 由AppDelegate 取得打开的数据库
SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate];
db = [[appDelegate db] retain];
}
return self;
}
// 子类中实现
-(NSString *)setTable:(NSString *)sql{
return NULL;
}
- (void)dealloc {
[db release];
[super dealloc];
}
@end
下面是访问TbNote 表格的类。
//TbNoteDao.h
#import <Foundation/Foundation.h>
#import "BaseDao.h"
@interface TbNoteDao : BaseDao {
}
-(NSMutableArray *)select;
-(void)insertWithTitle:(NSString *)title Body:(NSString *)body;
-(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body;
-(BOOL)deleteAt:(int)index;
@end
//TbNoteDao.m
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "TbNoteDao.h"
#import "TbNote.h"
@implementation TbNoteDao
-(NSString *)setTable:(NSString *)sql{
return [NSString stringWithFormat:sql, @"TbNote"];
}
// SELECT
-(NSMutableArray *)select{
NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
FMResultSet *rs = [db executeQuery:[self setTable:@"SELECT * FROM %@"]];
while ([rs next]) {
TbNote *tr = [[TbNote alloc]
initWithIndex:[rs intForColumn:@"id"]
Title:[rs stringForColumn:@"title"]
Body:[rs stringForColumn:@"body"]
];
[result addObject:tr];
[tr release];
}
[rs close];
return result;
}
// INSERT
-(void)insertWithTitle:(NSString *)title Body:(NSString *)body{
[db executeUpdate:[self setTable:@"INSERT INTO %@ (title, body) VALUES (?,?)"], title, body];
if ([db hadError]) {
NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
}
}
// UPDATE
-(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body{
BOOL success = YES;
[db executeUpdate:[self setTable:@"UPDATE %@ SET title=?, body=? WHERE id=?"], title, body, [NSNumber numberWithInt:index]];
if ([db hadError]) {
NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
success = NO;
}
return success;
}
// DELETE
- (BOOL)deleteAt:(int)index{
BOOL success = YES;
[db executeUpdate:[self setTable:@"DELETE FROM %@ WHERE id = ?"], [NSNumber numberWithInt:index]];
if ([db hadError]) {
NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
success = NO;
}
return success;
}
- (void)dealloc {
[super dealloc];
}
@end
为了确认程序正确,我们添加一个UITableView。使用initWithNibName 测试DAO。
//NoteController.h
#import <UIKit/UIKit.h>
@class TbNoteDao;
@interface NoteController : UIViewController <UITableViewDataSource, UITableViewDelegate>{
UITableView *myTableView;
TbNoteDao *tbNoteDao;
NSMutableArray *record;
}
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) TbNoteDao *tbNoteDao;
@property (nonatomic, retain) NSMutableArray *record;
@end
//NoteController.m
#import "NoteController.h"
#import "TbNoteDao.h"
#import "TbNote.h"
@implementation NoteController
@synthesize myTableView, tbNoteDao, record;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
tbNoteDao = [[TbNoteDao alloc] init];
[tbNoteDao insertWithTitle:@"TEST TITLE" Body:@"TEST BODY"];
// [tbNoteDao updateAt:1 Title:@"UPDATE TEST" Body:@"UPDATE BODY"];
// [tbNoteDao deleteAt:1];
record = [[tbNoteDao select] retain];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
myTableView.delegate = self;
myTableView.dataSource = self;
self.view = myTableView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [record count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
TbNote *tr = (TbNote *)[record objectAtIndex:indexPath.row];
cell.text = [NSString stringWithFormat:@"%i %@", [tr getIndex], tr.title];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[super dealloc];
}
@end
最后我们开看看连接DB,和添加ViewController 的处理。这一同样不使用Interface Builder。
//SqlSampleAppDelegate.h
#import <UIKit/UIKit.h>
@class FMDatabase;
@interface SqlSampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
FMDatabase *db;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) FMDatabase *db;
- (BOOL)initDatabase;
- (void)closeDatabase;
@end
//SqlSampleAppDelegate.m
#import "SqlSampleAppDelegate.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "NoteController.h"
@implementation SqlSampleAppDelegate
@synthesize window;
@synthesize db;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
if (![self initDatabase]){
NSLog(@"Failed to init Database.");
}
NoteController *ctrl = [[NoteController alloc] initWithNibName:nil bundle:nil];
[window addSubview:ctrl.view];
[window makeKeyAndVisible];
}
- (BOOL)initDatabase{
BOOL success;
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fm fileExistsAtPath:writableDBPath];
if(!success){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
success = NO;
}
if(success){
db = [[FMDatabase databaseWithPath:writableDBPath] retain];
if ([db open]) {
[db setShouldCacheStatements:YES];
}else{
NSLog(@"Failed to open database.");
success = NO;
}
}
return success;
}
- (void) closeDatabase{
[db close];
}
- (void)dealloc {
[db release];
[window release];
[super dealloc];
}
@end
|
|