最近抽空写了一个日记本小程序,为了练习一些知识点
一、用到的知识点
1、FMDB,自己封装了增删改查的方法
2、StoryBoard 画图,segue传值
3、自定义UIPickerView,可以移植,多类型操作
4、自定义cell、实体、手势操作
5、属性字符串练习
6、UIcollectView的简单使用
总之都是小白的写法,大牛请绕行。下面开始:
二、FMDB
1、导入所有这些h和m
framework添加libsqlite3.dylib
2、建立数据库模型
#import <Foundation/Foundation.h> @class FMDatabase;
#define DB_NAME @"long.sqlite"
@interface Database : NSObject { FMDatabase *db; } - (NSString*)SQL:(NSString*)sql inTable:(NSString*)table;
@end |
#import "Database.h" #import "FMDatabase.h" @implementation Database
- (id)init{ self = [super init]; if (self) { NSString *dbPath = [documentPathstringByAppendingPathComponent:DB_NAME]; db = [FMDatabase databaseWithPath:dbPath]; if ([db open]) { [db setShouldCacheStatements:YES]; debugLog(@"open db success"); }else { debugLog(@"failed to open db"); } } return self; } #pragma mark - 执行SQL语句 - (NSString*)SQL:(NSString *)sql inTable:(NSString *)table{ return [NSString stringWithFormat:sql,table]; } @end |
3、封装数据库操作
#define TABLE_NAME_NOTEBOOK @"NOTEBOOK"
@interface DatabaseOperation : Database
+ (id)sharedInstance; //单例
// 查找 - (NSMutableArray *) findByCriteria:(NSString *)criteria;//按条件查找 - (NoteBook *) findFirstByCriteria:(NSString *)criteria; //查找第一个 - (NSInteger) countByCriteria:(NSString *)criteria; //计数,满足条件的个数
// 插入 - (void) saveNoteBook:(NoteBook *)noteBook; //保存,插入 //- (void) saveNoteBooks:(NSArray *)noteBooks; //保存多个数据,对于多参数数据存数不对,需要调整
// 更新 - (BOOL) updateAtIndex:(NSInteger)index withNoteBook:(NoteBook *)noteBook;//更新
// 删除 - (BOOL) deleteAtIndex:(int)index; //删除
// 清空 - (BOOL) cleanTable:(NSString*)tableName; |
+ (id)sharedInstance { static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } #pragma mark - 建表 - (id)init{ self = [super init]; if (self) { if (![db tableExists:TABLE_NAME_NOTEBOOK]) { NSString *sql = [self SQL:@"create table if not exists '%@'('noteId' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'noteName' text,'noteTime' text,'noteStyle' text,'noteContent' text);"inTable:TABLE_NAME_NOTEBOOK]; BOOL result = [db executeUpdate:sql]; if (result) { debugLog(@"create table success"); }else{ debugLog(@"Fialed to create table"); } } debugLog(@"table exists"); [db close]; } return self; } #pragma mark - 查找 #pragma mark - 查找所有满足条件的数据 - (NSMutableArray*)findByCriteria:(NSString *)criteria{ NSMutableArray *resultArr = [[NSMutableArray alloc] initWithCapacity:0]; NSMutableString *sql = [NSMutableString stringWithString:[selfSQL:@"select * from %@" inTable:TABLE_NAME_NOTEBOOK]]; if (criteria!=nil) { [sql appendString:criteria]; } if ([db open]) { FMResultSet *resultSet = [db executeQuery:sql]; while ([resultSet next]) { //提取赋值 NoteBook *nb = [[NoteBook alloc] init]; nb.noteId = [resultSet intForColumn:@"noteId"]; nb.noteName = [resultSet stringForColumn:@"noteName"]; nb.noteTime = [resultSet stringForColumn:@"noteTime"]; nb.noteStyle = [resultSet stringForColumn:@"noteStyle"]; nb.noteContent = [resultSet stringForColumn:@"noteContent"]; [resultArr addObject:nb]; } [db close]; } return resultArr;
} #pragma mark - 查找第一个数据 - (NoteBook*)findFirstByCriteria:(NSString *)criteria{ NSMutableArray *resultArr = [[NSMutableArray alloc] initWithCapacity:0]; NSMutableString *sql = [NSMutableString stringWithString:[selfSQL:@"select * from %@" inTable:TABLE_NAME_NOTEBOOK]]; if (criteria!=nil) { [sql appendString:criteria]; } if ([db open]) { FMResultSet *result = [db executeQuery:sql]; while ([result next]) { NoteBook *nb = [[NoteBook alloc] init]; nb.noteId = [result intForColumn:@"noteId"]; nb.noteName = [result stringForColumn:@"noteName"]; nb.noteTime = [result stringForColumn:@"noteTime"]; nb.noteStyle = [result stringForColumn:@"noteStyle"]; nb.noteContent = [result stringForColumn:@"noteContent"]; [resultArr addObject:nb]; } [db close]; } if ([resultArr count]>0) { return [resultArr objectAtIndex:0]; }else{ return nil; }
} #pragma mark - 计数 - (NSInteger)countByCriteria:(NSString *)criteria{ NSInteger count = 0; NSMutableString *sql = [NSMutableString stringWithString:[selfSQL:@"select count(*) from %@" inTable:TABLE_NAME_NOTEBOOK]]; if (criteria!=nil) { [sql appendString:criteria]; } if ([db open]) { FMResultSet *res = [db executeQuery:sql]; while ([res next]) { count = [res intForColumnIndex:0]; } [db close]; } return count; } #pragma mark -保存 #pragma mark -- 保存单个数据 - (void)saveNoteBook:(NoteBook *)noteBook{ NSInteger index = noteBook.noteId; if (index >= 0) { [self updateAtIndex:index withNoteBook:noteBook]; }else { // NSString *noteNamestr = [[NSString alloc] initWithString:noteBook.noteName]; NSString *noteTimestr = [[NSString alloc] initWithString:noteBook.noteTime]; NSString *noteStylestr = [[NSString alloc] initWithString:noteBook.noteStyle]; NSString *noteContentstr = [[NSString alloc] initWithString:noteBook.noteContent]; //db if ([db open]) { [db beginTransaction]; NSString *sql = [self SQL:@"insert into %@ ('noteName','noteTime','noteStyle','noteContent')values(?,?,?,?);"inTable:TABLE_NAME_NOTEBOOK]; BOOL res = [dbexecuteUpdate:sql,noteNamestr,noteTimestr,noteStylestr,noteContentstr]; if (res) { debugLog(@"插入数据成功"); }else{ debugLog(@"插入数据失败"); } [db commit]; [db close]; } } } #pragma mark --存储 多个数据 //存储多个数据,对于多参数数据,不对,需要调整 - (void)saveNoteBooks:(NSArray *)noteBooks{ NSMutableArray *values = [[NSMutableArray alloc] initWithCapacity:0]; for (NoteBook *nb in noteBooks) { NSString *noteName = [NSString stringWithString:nb.noteName]; NSMutableString *value = [[NSMutableStringalloc]initWithFormat:@"%@",noteName]; [values addObject:value]; } if ([values count]>0) { if ([db open]) { [db beginTransaction]; NSString *compinentStr = [values componentsJoinedByString:@","]; NSString *sql = [self SQL:@"insert or ignore into %@ ('noteName') values ?" inTable:TABLE_NAME_NOTEBOOK]; BOOL res = [db executeUpdate:sql,compinentStr]; if (res) { debugLog(@"save data success"); }else{ debugLog(@"Failed to save data"); } [db commit]; [db close]; } } } #pragma mark - 更新 - (BOOL)updateAtIndex:(NSInteger)index withNoteBook:(NoteBook *)noteBook{ // NSNumber *indexID = [[NSNumber alloc]initWithInteger:noteBook.noteId]; BOOL success = YES; NSString *noteNamestr = [[NSString alloc] initWithString:noteBook.noteName]; NSString *noteTimestr = [[NSString alloc] initWithString:noteBook.noteTime]; NSString *noteStylestr = [[NSString alloc] initWithString:noteBook.noteStyle]; NSString *noteContentstr = [[NSString alloc] initWithString:noteBook.noteContent]; if ([db open]) { [db beginTransaction]; BOOL res = [db executeUpdate:[self SQL:@"update %@ set noteName = ?,noteTime = ?,noteStyle = ?,noteContent = ? where noteId = ?"inTable:TABLE_NAME_NOTEBOOK],noteNamestr,noteTimestr,noteStylestr,noteContentstr,indexID]; if (res) { debugLog(@"更新成功"); }else{ debugLog(@"更新失败"); } [db commit]; [db close]; } if ([db hadError]) { debugLog(@"err %d:%@",[db lastErrorCode],[db lastErrorMessage]); success = NO; } return success;
} #pragma mark - 删除 - (BOOL)deleteAtIndex:(int)index{ BOOL success = YES; if ([db open]) { BOOL res = [db executeUpdate:[self SQL:@"delete from %@ where noteId = ? " inTable:TABLE_NAME_NOTEBOOK],[NSNumber numberWithInt:index]]; if (res) { debugLog(@"delete success"); }else{ debugLog(@"Failed to delete"); success = NO; } [db close]; // if ([db hadError]) { // debugLog(@"err %d:%@",[db lastErrorCode],[db lastErrorMessage]); // success = NO; // }else{ // [db clearCachedStatements]; // } } return success; } #pragma mark - 清空表 - (BOOL)cleanTable:(NSString*)tableName{ BOOL success = YES; if ([db open]) { if (tableName) { BOOL res = [db executeUpdate:[NSString stringWithFormat:@"delete from %@",tableName]]; if (res) { debugLog(@"clean table success"); }else{ debugLog(@"Failed to clean table"); success = NO; } } [db close]; }
return success; } @end |
上面都是小白的写法,献丑了,如果你也是小白可以看看,FMDB还是很不错的
三、自定义PickerView
#import <UIKit/UIKit.h>
typedef enum { PickerTypeNormal = 0, //通用 PickerTypeDate, //日期 PickerTypeSex, //性别 PickerTypeStyle //类型 }PickerType;
//代理 @protocol SSLPickerViewDelegate <NSObject>
- (void)selectByType:(PickerType)type andTitle:(NSString *)title; - (void)finishSelect:(PickerType)type;
@end
@interface SSLPickerView : UIView<UIPickerViewDelegate,UIPickerViewDataSource> { PickerType type; int currentIndex; NSArray *styleArray;
} @property (weak, nonatomic) id<SSLPickerViewDelegate>parent; @property (weak, nonatomic) IBOutlet UIPickerView *sslPickerView; @property (weak, nonatomic) IBOutlet UIView *selectView; //取消、完成示图 @property (copy, nonatomic) NSString *dateString; //日期字段 @property (copy, nonatomic) NSString *styleString; //类型字段 @property (copy, nonatomic) NSString *sexString; //性别字段
//方法 - (IBAction)cancelButton:(id)sender; - (IBAction)selectDone:(id)sender;
- (id)initWithType:(PickerType)pickerType delegate:(id<SSLPickerViewDelegate>)delegate; - (void)showInView:(UIView*)view; - (void)closePickerView;
|
#define kDuration 0.3 #import "SSLPickerView.h" #import <QuartzCore/CALayer.h>
@implementation SSLPickerView @synthesize parent; @synthesize dateString,sexString,styleString; @synthesize sslPickerView; @synthesize selectView;
- (id)initWithType:(PickerType)pickerType delegate:(id<SSLPickerViewDelegate>)delegate{ self = [[[NSBundle mainBundle]loadNibNamed:@"SSLPickerView" owner:selfoptions:nil] objectAtIndex:0]; if (self) { parent = delegate; self.backgroundColor = [UIColor colorWithRed:235.0/255.0green:235.0/255.0 blue:241.0/255.0 alpha:1.0]; sslPickerView.delegate = self; sslPickerView.dataSource = self;
//取消、完成示图 CGRect frame = selectView.frame; frame.size.width = kWidth; selectView.frame = frame; selectView.layer.borderColor = [[UIColor lightGrayColor]CGColor]; selectView.layer.borderWidth = 0.5f;
//button UIButton *finishButton = (UIButton*)[selectView viewWithTag:6]; if (finishButton) { frame = finishButton.frame; frame.origin.x = frame.origin.x/320*kWidth; finishButton.frame = frame; } UIButton *cancelButton = (UIButton*)[selectView viewWithTag:5]; if (cancelButton) { frame = cancelButton.frame; frame.origin.x = frame.origin.x/320*kWidth; cancelButton.frame = frame; } // type = pickerType; switch (type) { case PickerTypeDate: { [sslPickerView removeFromSuperview]; UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 60, kWidth, 220)]; datePicker.datePickerMode = UIDatePickerModeDate; datePicker.maximumDate = [NSDate date]; datePicker.backgroundColor = [UIColor clearColor]; [datePicker setTimeZone:[NSTimeZonetimeZoneWithName:@"Asia/Shanghai"]]; [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged]; [self addSubview:datePicker];
} break; case PickerTypeStyle: { styleArray = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"PickerStyle" ofType:@"plist"]]; [sslPickerView selectRow:currentIndex inComponent:0animated:YES];
} break;
default: break; }
} return self; } #pragma mark - 日期 - (void)dateChanged:(id)sender{ UIDatePicker *dateP = (UIDatePicker*)sender; [dateP setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; NSString *theTime = [NSString stringWithFormat:@"%@",[dateP date]]; [parent selectByType:type andTitle:[theTime substringToIndex:10]];//回调代理 } - (void)showInView:(UIView *)view { CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = kDuration; animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.type = kCATransitionPush; animation.subtype = kCATransitionFromTop; [self setAlpha:1.0f]; [self.layer addAnimation:animation forKey:@"LocatePickerView"];
self.frame = CGRectMake(0, view.frame.size.height - self.frame.size.height-topBarheight, kWidth, self.frame.size.height); [view addSubview:self]; } #pragma mark - PickerView - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return 1; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ NSInteger number = 0; if (type==PickerTypeSex) { number = 2; }else if (type==PickerTypeStyle){ number = [styleArray count]; } return number;
} - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ NSString *title = @""; switch (type) { case PickerTypeSex: { title = (row==0)?@"男":@"女"; } break; case PickerTypeStyle: { title = [styleArray objectAtIndex:row]; } break; default: break; } return title; }
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ switch (type) { case PickerTypeSex: [parent selectByType:type andTitle:(row==0)?@"男":@"女"]; break; case PickerTypeStyle: [parent selectByType:type andTitle:[styleArrayobjectAtIndex:row]]; break;
default: break; } }
#pragma mark - 取消,完成动作 - (IBAction)cancelButton:(id)sender { switch (type) { case PickerTypeSex: [parent selectByType:type andTitle:sexString]; break; case PickerTypeDate: [parent selectByType:type andTitle:dateString]; break; case PickerTypeStyle: [parent selectByType:type andTitle:styleString]; break;
default: break; } CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = kDuration; animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseOut]; animation.type = kCATransitionPush; animation.subtype = kCATransitionFromBottom; [self setAlpha:0.0f]; [self.layer addAnimation:animation forKey:@"sslPickerView"]; [parent finishSelect:type];
}
- (IBAction)selectDone:(id)sender { CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = kDuration; animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.type = kCATransitionPush; animation.subtype = kCATransitionFromBottom; [self setAlpha:0.0f]; [self.layer addAnimation:animation forKey:@"sslPickerView"]; [parent finishSelect:type]; } @end |
注意了;这里是有代理方法的,需要实现奥
![](/cms/uploads/allimg/150526/-1_150526172244_1.png)
四、属性字符串的简单实用结合storyBoard
//名字 NSDictionary *attributesName = @{NSForegroundColorAttributeName:[UIColorgreenColor], NSFontAttributeName:[UIFontfontWithName:@"Zapfino" size:18.0]}; NSAttributedString *attributedTextName = [[NSAttributedString alloc] initWithString:self.detialNoteBook.noteName attributes:attributesName]; detialName.attributedText = attributedTextName;
//类型 NSDictionary *attributeStyle = @{NSForegroundColorAttributeName:[UIColorredColor], NSFontAttributeName:[UIFontfontWithName:@"HelveticaNeue" size:14.0]}; NSAttributedString *attributeTextStyle = [[NSAttributedString alloc] initWithString:self.detialNoteBook.noteStyle attributes:attributeStyle]; detialType.attributedText = attributeTextStyle;
//时间 NSDictionary *attributeTime = @{NSForegroundColorAttributeName:[UIColorredColor], NSFontAttributeName:[UIFontfontWithName:@"HelveticaNeue" size:14.0]}; NSAttributedString *attributeTextTime = [[NSAttributedString alloc] initWithString:self.detialNoteBook.noteTime attributes:attributeTime]; detialTime.attributedText = attributeTextTime;
//内容 NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; paragraph.alignment = NSTextAlignmentJustified; paragraph.firstLineHeadIndent = 20.0; paragraph.paragraphSpacingBefore = 10.0; paragraph.lineSpacing = 10; paragraph.hyphenationFactor = 5.0;
NSDictionary *attributeNoteContent = @{NSForegroundColorAttributeName:[UIColor blackColor], NSBackgroundColorAttributeName:[UIColor magentaColor], NSParagraphStyleAttributeName:paragraph, NSFontAttributeName:[UIFontfontWithName:@"TrebuchetMS-Bold" size:13.0] };
NSAttributedString *attributeText = [[NSAttributedString alloc] initWithString:self.detialNoteBook.noteContentattributes:attributeNoteContent]; detialContent.attributedText = attributeText; |
总之里面用到了很多细节的知识点,但是很简单,可以作为入门级选手学习资料。
内部无图片,纯纯的原生代码效果,
新建页面
查看详情