當前狀態欄
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
設置keywindow 的view ,可以放在全部view的最上層,不會被其他view填充[[UIApplication sharedApplication].keyWindow addSubview:_nav.view];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rightPress:) object:rightItem];
取消上一次的事件
自定義導航欄背景
#import "UINavigationBar+customBar.h"
#import <QuartzCore/QuartzCore.h>
@implementation UINavigationBar (customBar)
- (void)drawRect:(CGRect)rect
{
[[UIImage imageNamed:@"u7_normal"] drawInRect:rect];
}
- (void)customNavigationBar
{
if ([self respondsToSelector:@selector(setBackgroundColor:)]) {
[self setBackgroundImage:[UIImage imageNamed:@"u7_normal"] forBarMetrics:UIBarMetricsDefault];
} else {
[self drawRect:self.bounds];
}
[self drawRoundCornerAndShadow];
}
- (void)drawRoundCornerAndShadow {
CGRect bounds = self.bounds;
bounds.size.height +=10;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;
[self.layer addSublayer:maskLayer];
self.layer.mask = maskLayer;
self.layer.shadowOffset = CGSizeMake(3, 3);
self.layer.shadowOpacity = 0.7;
self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
}
@end
定製導航欄按鈕
//
// ILBarButtonItem.m
// Version 1.0
// Created by Isaac Lim (isaacl.net) on 1/1/13.
//
#import "ILBarButtonItem.h"
@interface ILBarButtonItem() {
id customTarget;
UIButton *customButton;
}
@end
@implementation ILBarButtonItem
- (id)initWithImage:(UIImage *)image frame:(CGRect)frame
selectedImage:(UIImage *)selectedImage
target:(id)target action:(SEL)action {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:frame];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[btn setImage:image forState:UIControlStateNormal];
[btn setImage:selectedImage forState:UIControlStateHighlighted];
/* Init method inherited from UIBarButtonItem */
self = [[ILBarButtonItem alloc] initWithCustomView:btn];
if (self) {
/* Assign ivars */
customButton = btn;
customImage = image;
customSelectedImage = selectedImage;
customTarget = target;
customAction = action;
}
return self;
}
+ (ILBarButtonItem *)barItemWithImage:(UIImage*)image frame:(CGRect)frame
selectedImage:(UIImage*)selectedImage
target:(id)target
action:(SEL)action
{
return [[ILBarButtonItem alloc] initWithImage:image frame:frame
selectedImage:selectedImage
target:target
action:action];
}
- (void)setCustomImage:(UIImage *)image {
customImage = image;
[customButton setImage:image forState:UIControlStateNormal];
}
- (void)setCustomSelectedImage:(UIImage *)image {
customSelectedImage = image;
[customButton setImage:image forState:UIControlStateHighlighted];
}
- (void)setCustomAction:(SEL)action {
customAction = action;
[customButton removeTarget:nil
action:NULL
forControlEvents:UIControlEventAllEvents];
[customButton addTarget:customTarget
action:action
forControlEvents:UIControlEventTouchUpInside];
}
@end
原界面不東,彈出一個新的UINavigationControl
- (void)showCollection: (NSInteger)row
{
CollectionView *collection = [[CollectionView alloc] init];
collection.title = [_toolsData objectAtIndex:row];
[self setNavTitleView:collection];
collection.back = ^() {
[_nav release];
};
_nav = [[UINavigationController alloc] initWithRootViewController:collection];
[collection release];
[_nav.navigationBar customNavigationBar];
[[UIApplication sharedApplication].keyWindow addSubview:_nav.view];
__block CGRect frame = _nav.view.frame;
frame.origin.x = CGRectGetWidth(frame);
_nav.view.frame = frame;
[UIView animateWithDuration:0.5 animations:^(){
frame.origin.x = 0.f;
_nav.view.frame = frame;
}];
}
#pragma mark navigator item action
- (void)backBarButtonItem
{
CGRect frame = self.navigationController.view.frame;
frame.origin.x = screenWidth;
[UIView animateWithDuration:0.5 animations:^{
self.navigationController.view.frame = frame;
} completion:^(BOOL finished){
if (finished) {
[self.navigationController.view removeFromSuperview];
self.back();
}
}];
}
原界面不動,彈出一個view(動畫效果而已)
ShareView *shareView = [[ShareView alloc] initWithFrame:CGRectMake(screenWidth, 0, screenWidth, screenHeight)];
[self setNavTitleView:shareView titleName:[_toolsData objectAtIndex:indexPath.row]];
[app.window.rootViewController.view insertSubview:shareView aboveSubview:app.window.rootViewController.view];
CGRect frame = shareView.frame;
frame.origin.x = 0;
[UIView animateWithDuration:0.5 animations:^(){
shareView.frame = frame;
}];
[shareView release];
- (void)backButton
{
CGRect frame = self.frame;
frame.origin.x = screenWidth;
[UIView animateWithDuration:0.5 animations:^{
self.frame = frame;
} completion:^(BOOL finished){
[self removeFromSuperview];
}];
}
自動單擊UITableView的cell
if ([_data count] <= 0) {
[self addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew context:nil];
}
[self tableView:_tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[_tableView reloadData];
[self tableView:_tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}
self.navigationItem.hidesBackButton = YES; //隱藏點擊其它返回按鈕時,出現的默認返回按鈕
字符串長度或高度計算方式
#pragma mark calulator stringOfSize;
- (CGRect)stringOfSize:(NSString *)str font:(UIFont *)font frame:(CGRect)frame
{
CGSize titleSize = [str sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
frame = CGRectMake(frame.origin.x, frame.origin.y, titleSize.width, titleSize.height);
return frame;
}
UIWebView設置頁面字體大小
- (void)setSize:(CGFloat)size
{
_fontSize = size;
NSString *jsString = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-size: %f;}\n"
"</style> \n"
"</head> \n"
"<body>%@</body> \n"
"</html>", size, _ariticle.intro];
[_webView loadHTMLString:jsString baseURL:nil];
}
#pragma mark UIWebView delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//左右滾動條
NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
[webView stringByEvaluatingJavaScriptFromString:meta];
[webView stringByEvaluatingJavaScriptFromString:
@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth=280;" //縮放係數
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"myimg.height = myimg.height * (maxwidth/oldwidth);"
"}"
"};"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
//設置scrollview 高度
CGRect frame = webView.frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeMake(screenWidth, 0)];
frame.size = fittingSize;
webView.frame = frame;
NSLog(@"內容字體變小 高度有問題, %f", frame.size.height);
//高度不能一直加
_scrollView.contentSize = CGSizeMake(screenWidth, _allHeight + webView.frame.size.height);
}
#pragma mark UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//左右滾動條
NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
[webView stringByEvaluatingJavaScriptFromString:meta];
}
網絡請求服務
#import <Foundation/Foundation.h>
typedef void (^FinishNet) (NSMutableData *data);
@interface NetRequest : NSMutableURLRequest <NSURLConnectionDataDelegate>
@property (nonatomic, retain) NSMutableData *data;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, copy) FinishNet block;
- (void)startAsynrc;
- (void)cancel;
@end
#import "NetRequest.h"
@implementation NetRequest
- (void)startAsynrc
{
self.data = [NSMutableData data];
self.connection = [NSURLConnection connectionWithRequest:self delegate:self];
}
- (void)cancel
{
[self cancel];
}
#pragma mark NSURLConnectionDataDelegate
// receive data
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.data appendData:data];
}
// finish receive
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.block(self.data);
}
//error
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"數據連接錯誤:%@", error);
}
@end
#import <Foundation/Foundation.h>
typedef void (^completion)(id result);
@interface NetDeal : NSObject
+ (void)getNetInfo:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get block:(completion)block;
+ (void)getNetFile:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get block:(completion)block;
//同步獲取數據
+ (id)getNetFileSynch:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get;
@end
#import "NetDeal.h"
#import "NetRequest.h"
@implementation NetDeal
// json
+ (void)getNetInfo:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get block:(completion)block
{
//封裝參數
if (params != nil) {
NSMutableString *urlnew = [NSMutableString stringWithString:urlstring];
for (int i = 0; i < [params count]; i ++) {
[urlnew appendFormat:@"&%@", [params objectAtIndex:i]];
}
urlstring = urlnew;
}
// 轉換成NSURL
NSURL *url = [NSURL URLWithString:urlstring];
NetRequest *request = [NetRequest requestWithURL:url];
[request setTimeoutInterval:30];
if (!get) {
//do smo
}
request.block = ^(NSMutableData *data){
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block(result);
};
[request startAsynrc];
}
//file
+ (void)getNetFile:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get block:(completion)block
{
if (params != nil) {
NSMutableString *urlNew = [NSString stringWithString:urlstring];
for (int i = 0; i < [params count]; i ++) {
[urlNew appendFormat:@"&%@", [params objectAtIndex:i]];
}
urlstring = urlNew;
}
NSURL *url = [NSURL URLWithString:urlstring];
NetRequest *request = [NetRequest requestWithURL:url];
[request setTimeoutInterval:30];
if (!get) {
}
request.block = ^(NSMutableData *data){
block(data);
};
[request startAsynrc];
}
//同步獲取數據
+ (id)getNetFileSynch:(NSString *)urlstring params:(NSArray *)params isGet:(BOOL)get
{
if (params != nil) {
NSMutableString *urlNew = [NSString stringWithString:urlstring];
for (int i = 0; i < [params count]; i ++){
[urlNew appendFormat:@"&%@", [params objectAtIndex:i]];
}
urlstring = urlNew;
}
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10] autorelease];
NSError *error = nil;
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (error) {
NSLog(@"接受數據失敗:%@", error);
return nil;
}
return received;
}
@end
數據庫相關操作(使用FMDB)
#import <Foundation/Foundation.h>
@interface DBService : NSObject
//查詢
- (NSArray *)query:(NSString *)sql;
//增刪改
- (BOOL)update:(NSString *)sql;
@end
#import "DBService.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "DBConnection.h"
@implementation DBService
//查詢
- (NSArray *)query:(NSString *)sql
{
FMDatabase *base = [[DBConnection getInstance] loadDB:collectionDataBaseName];
NSMutableArray *list = nil;
@try {
FMResultSet *result = [base executeQuery:sql];
list = [[[NSMutableArray alloc]init] autorelease];
while ([result next]) {
int column = [result columnCount];
for (int i = 0; i < column; i ++){
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:[result stringForColumnIndex:i] forKey:[result columnNameForIndex:i]];
[list addObject:dic];
[dic release];
}
}
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
@finally {
[base close];
}
return list;
}
//增刪改
- (BOOL)update:(NSString *)sql
{
BOOL result = NO;
FMDatabase *base = [[DBConnection getInstance] loadDB:collectionDataBaseName];
@try {
result = [base executeUpdate:sql];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
}
@finally {
[base close];
}
return result;
}
@end
#import <Foundation/Foundation.h>
@class FMDatabase;
@interface DBConnection : NSObject
+ (DBConnection *)getInstance;
- (FMDatabase *)loadDB:(NSString *)dbName;
@end
#import "DBConnection.h"
#import "FMDatabase.h"
@implementation DBConnection
static DBConnection *instance = nil;
+ (DBConnection *)getInstance
{
@synchronized(self)
{
if (instance == nil) {
instance = [[self alloc]init];
}
}
return instance;
}
- (FMDatabase *)loadDB:(NSString *)dbName
{
FMDatabase *db = [FMDatabase databaseWithPath:[[ToolsClass getDocumentPath] stringByAppendingPathComponent:dbName]];
if (![db open]) {
[db release];
NSLog(@"can't open it");
return nil;
}
return db;
}
@end