您的位置:首页 > 移动开发 > IOS开发

Ios小记整理

2015-09-28 15:59 337 查看
#pragmamark - 获取当前手机的具体型号
//+(NSString*)deviceVersion
//{
// // 需要#import"sys/utsname.h"
// struct utsname systemInfo;
// uname(&systemInfo);
// NSString *deviceString = [NSStringstringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
//
// //CLog(@"%@",deviceString);
//
// if ([deviceStringisEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
// if ([deviceString isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
// if ([deviceStringisEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
// if ([deviceStringisEqualToString:@"iPhone3,1"]) return @"iPhone 4";
// if ([deviceStringisEqualToString:@"iPhone3,2"]) return @"Verizon iPhone 4";
// if ([deviceStringisEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
// if ([deviceStringisEqualToString:@"iPhone5,2"]) return @"iPhone 5";
//}
1.1.图片灰度图的产生(公式):
单个像素点的rgb值一样:result = red*30%+green*59%+blue*11%
调节亮度就改变该值(result)。

1.2.图片灰度图
-(UIImage*)getGrayImage:(UIImage*)sourceImage
{
int width =sourceImage.size.width;
int height =sourceImage.size.height;
CGColorSpaceRefcolorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context= CGBitmapContextCreate(nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
if (context == NULL){
return nil;
}
CGContextDrawImage(context,CGRectMake(0, 0, width, height),sourceImage.CGImage);
UIImage *grayImage =[UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
returngrayImage;
}
其中,CGColorSpaceCreateDeviceGray会创建一个设备相关的灰度颜色空间的引用

1.3.图片反射度设置(公式):
单个像素点的rgb值:result = 底图分量(r,g,b)*(1-r)+反射分量(r,g,b)*r; r为反射度,其值为(0-1);
调节亮度就改变该值(result)。

2.根据图片创建位图
- (void)createRGBABitmapContextFromImage:(CGImageRef)inImage withContectRef:(CGContextRef*)contextRef
{//根据图片大小创建一个位图
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
size_t pixelsWide =
CGImageGetWidth(inImage);
size_t pixelsHigh =
CGImageGetHeight(inImage);
bitmapBytesPerRow = (pixelsWide* 4);
bitmapByteCount =(bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();

if (colorSpace ==
NULL)
{
return;
}
bitmapData = malloc(bitmapByteCount );
if (bitmapData ==
NULL)
{
CGColorSpaceRelease( colorSpace );
return;
}
*contextRef = CGBitmapContextCreate(bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);

if ((*contextRef) ==
NULL)
{
free (bitmapData);
}
CGColorSpaceRelease( colorSpace );
}

3.由位图得到图片数据

- (void*)getImageData:(UIImage*)image
{
void* imageData;
if (imageData == NULL)
imageData= malloc(4 * image.size.width * image.size.height);

CGColorSpaceRef cref =CGColorSpaceCreateDeviceRGB();
CGContextRef gc = CGBitmapContextCreate(imageData,
image.size.width,image.size.height,
8,image.size.width*4,
cref,kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(cref);
UIGraphicsPushContext(gc);

[imagedrawAtPoint:CGPointMake(0.0f, 0.0f)];

UIGraphicsPopContext();
CGContextRelease(gc);

return imageData;
}

4.判断touch到子视图或离开视图
-(void)touchesMoved:(NSSet *)touches withEvent(UIEvent*)event
{

UITouch *touch=[touches anyObject];

if (![self pointInside:[touch locationInView:self]withEvent:nil])
{

NSLog(@"touches moved outsidethe view");

}
else
{

UIView *hitView=[selfhitTest:[[touches anyObject] locationInView:self] withEvent:nil];

if (hitView==self)
{

NSLog(@"touches moved in the view");

}
else
{

NSLog(@"touches moved in the subview");

}

}

}
5.判iOS移除全部subview和判断子视图是否加上

NSArray *views = [self subviews];
for(UIVIew* view in views)
{
[view removefromsuperview];
}
判断子视图是否加了
for(UIView *view = self.view.subViews)
{

if(View isKindOfCless:[OneViewObject class])
{

BOOL needAddToViewFlag = YES;

for(UIView *view = self.view.subViews)
{

if(View isKindOfCless:[OneViewObject class])
{

needAddToViewFlag = NO;

}

}

if (needAddToViewFlag)
{

[self.view addSubview:someView];

}

6.软键盘隐藏和移动键盘挡住的视图
方法3:在窗口的最底层添加一个320*480的UIControl控件:

UIControl *backGroundControl =[[UIControl alloc] initWithFrame:
CGRectMake(0, 0, 320, 480)];
backGroundControl.backgroundColor =[UIColor clearColor];
[backGroundControl addTarget:self
action:@selector(backgroundTab)
forControlEvents:UIControlEventTouchUpInside];
[window addSubview:backGroundControl];
定义一个方法
- (void)backgroundTab

{

[field resignFirstResponder];

}
怎么把键盘上的return改成DonetextField.returnKeyType=UIReturnKeyDone;
把textField里面输入的文字改成密文,textField.secureTextEntry=YES;

移动键盘上面的文本框
当系统收到显示键盘的请求时,就从屏幕的底部滑出键盘,并将它放在应用程序内容的上方。由于键盘位于您的内容的上面,所以有可能遮掩住用户希望编辑的文本对象。如果这种情况发生,就必须对内容进行调整,使目标对象保持可见。

需要做的调整通常包括暂时调整一或多个视图的尺寸和位置,从而使文本对象可见。管理带有键盘的文本对象的最简单方法是将它们嵌入到一个UIScrollView(或其子类,如UITableView)对象。当键盘被显示出来时,您需要做的只是调整滚动视图的尺寸,并将目标文本对象滚动到合适的位置。为此,在UIKeyboardDidShowNotification通告的处理代码中需要进行如下操作:

[list=1]取得键盘的尺寸。

将滚动视图的高度减去键盘的高度。

将目标文本框滚动到视图中。

图5-6演示了一个简单的应用程序如何处理上述的几个步骤。该程序将几个文本输入框嵌入到UIScrollView对象中,当键盘出现时,通告处理代码首先调整滚动视图的尺寸,然后用UIScrollView类的scrollRectToVisible:animated:方法将被触击的文本框滚动到视图中。

图5-6 调整内容的位置,使其适应键盘

请注意:在配置滚动视图时,请务必为所有的内容视图配置恰当的自动尺寸调整规则。在之前的图中,文本框实际上是一个UIView对象的子视图,该UIView对象又是UIScrollView对象的子视图。如果该UIView对象的UIViewAutoresizingFlexibleWidthUIViewAutoresizingFlexibleHeight选项被设置了,则改变滚动视图的边框尺寸会同时改变它的边框,因而可能导致不可预料的结果。禁用这些选项可以确保该视图保持尺寸不变,并正确滚动。
程序清单5-1显示了如何注册接收键盘通告和如何实现相应的处理器方法。这段代码是由负责滚动视图管理的视图控制器实现的,其中scrollView变量是一个指向滚动视图对象的插座变量。每个处理器方法都从通告的info对象取得键盘的尺寸,并根据这个尺寸调整滚动视图的高度。此外,keyboardWasShown:方法的任务是将当前活动的文本框矩形滚入视图,该文本框对象存储在一个定制变量中(在本例子中名为activeField),该变量是视图控制器的一个成员变量,在textFieldDidBeginEditing:委托方法中进行赋值,委托方法本身的代码显示在程序清单5-2中(在这个例子中,视图控制器同时也充当所有文本输入框的委托)。
程序清单5-1 处理键盘通告

// Call this method somewhere in your viewcontroller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotificationobject:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotificationobject:nil];
}

// Called when the UIKeyboardDidShowNotificationis sent.
-(void)keyboardWasShown:(NSNotification*)aNotification
{
if (keyboardShown)
return;

NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [infoobjectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Resize the scroll view (which is the rootview of the window)
CGRect viewFrame = [scrollView frame];
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;

// Scroll the active text field into view.
CGRect textFieldRect = [activeField frame];
[scrollView scrollRectToVisible:textFieldRectanimated:YES];

keyboardShown = YES;
}

// Called when theUIKeyboardDidHideNotification is sent
-(void)keyboardWasHidden:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [infoobjectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Reset the height of the scroll view to its originalvalue
CGRect viewFrame = [scrollView frame];
viewFrame.size.height += keyboardSize.height;
scrollView.frame = viewFrame;

keyboardShown = NO;
}

上面程序清单中的keyboardShown变量是一个布尔值,用于跟踪键盘是否可见。如果您的用户界面有多个文本输入框,则用户可能触击其中的任意一个进行编辑。发生这种情况时,虽然键盘并不消失,但是每次开始编辑新的文本框时,系统都会产生UIKeyboardDidShowNotification通告。您可以通过跟踪键盘是否确实被隐藏来避免多次减少滚动视图的尺寸。

7.隐藏状态栏
隐藏状态栏:
[[UIApplication shareApplication] setStatusBarHidden: YESanimated:NO]

横屏:
[[UIApplication shareApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].
orientation == UIInterfaceOrientationLandscapeLeft
window=[[UIWindow alloc] initWithFrame:[UIScreenmainScreen] bounds];全屏

自动适应父视图大小:
aView.autoresizingSubviews = YES;
aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth| UIViewAutoresizingFlexibleHeight);

8.释放webview缓存
NSURLCache
*sharedCache =
[[NSURLCache alloc]initWithMemoryCapacity:0 diskCapacity:0
diskPath:nil];
[NSURLCachesetSharedURLCache:sharedCache];

//Clear All Cookies
for(NSHTTPCookie
*cookiein
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{

//if([[cookie domain]isEqualToString:someNSStringUrlDomain]) {

[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];

}

9.得到画图所用的时间
- (void)drawRect:(CGRect)rect {
if (CGRectEqualToRect(rect,imageRect)) {
uint64_t start = mach_absolute_time();
[image drawAtPoint:imagePoint];
uint64_t drawTime = mach_absolute_time() - start;

NSString *text = [[NSString alloc] initWithFormat:@"%ld", drawTime];
UILabel *label = (UILabel *)[self viewWithTag:LABEL_TAG];
label.text = text;
[text release];
}
}

10.获取当前app的名称和版本号

C代码

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

// app名称

NSString *name = [infoDictionary objectForKey:@"CFBundleDisplayName"];

// app版本

NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

// app build版本

NSString *build = [infoDictionary objectForKey:@"CFBundleVersion"];

UILabel根据text自动调整大小

C代码

label.text = @"**********";

CGRect frame = label.frame;
frame.size.height = 10000; // 设置一个很大的高度

label.frame = frame;
[label sizeToFit];
frame.size.height = label.frame.size.height;
label.frame = frame;

直接拨打有分机号的电话

C代码

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://01011112222,3333"]];

11.将void *转为图片
void *imageData=malloc(320*480*32);
CGDataProviderRef dataProvider =
CGDataProviderCreateWithCFData((CFMutableDataRef)imageData);
CGImageRef maskingImage =
CGImageMaskCreate(320,480,
8, 8,
32*320, dataProvider,
NULL, YES);
CGDataProviderRelease(dataProvider);
free(imageData);

12.旋转(镜像)图片
[UIImage imageWithCGImage:(CGImageRef) scale:(CGFloat)orientation:(UIImageOrientation)];

13.动态图片显示

使用UIWebView可以显示.
NSString*html = [NSString stringWithFormat:@"<img src ='file://%@/test.gif'>", [[NSBundle mainBundle] bundlePath]];

14.应用图标右上角的提示小红圈的实现
[[UIApplicationsharedApplication]setApplicationIconBadgeNumber:2];
15.一个问题关于清除本地推送数据 local notification
通过服务器推送时,进入游戏, “通知中心”
会清除掉数据。
但是本地推送我通过“通知中心”点进来,“通知中心”中还继续显示N多条信息,有清除方法吗?
[[UIApplication sharedApplication]scheduledLocalNotifications].count
为0 因为都已经推送出去了。

最佳答案
[UIApplication sharedApplication]cancelAllLocalNotifications];
16.localnotification在具体时间推送的问题
代码贴上来
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
NSString *sZer = @"00:00:00";
[timeFormatter setDateFormat:@"HH:mm:ss"];
NSDate *zer = [timeFormatter dateFromString:sZer];

[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *notify = [[UILocalNotification alloc] init];
notify.fireDate = zer;
notify.alertBody = @"xxxx";
notify.timeZone = [NSTimeZone defaultTimeZone];
notify.soundName = UILocalNotificationDefaultSoundName;
notify.applicationIconBadgeNumber = days;

[[UIApplication sharedApplication] scheduleLocalNotification:notify];
他不能在00:00:00推送而是直接在程序运行时推送(代码位于viewdidload里面)
程序定义了一个NSTimer

最佳答案
notify.fireDate不是时间,而是距离推送的时间
17.iphoneno architectures to compile for
(arches =i386,valid_archs = armv6 armv7)错误解决办法

在targets--->Bulid Settings选项下面的Architectures一栏里,在ValidArchitectures里加入一项i386,问题解决。
18.UIView背景颜色渐变
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, 320, 480, 8, 4 * 320, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
// Draw Gradient Here
CGContextDrawLinearGradient(bitmapContext, myGradient, CGPointMake(0.0f, 0.0f), CGPointMake(320.0f, 480.0f), );
05
// Create a CGImage from context
06
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
07
// Create a UIImage from CGImage
08
UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
09
// Release the CGImage
10
CGImageRelease(cgImage);
11
// Release the bitmap context
12
CGContextRelease(bitmapContext);
13
// Create the patterned UIColor and set as background color
14
[targetView setBackgroundColor:[UIColor colorWithPatternImage:image]];

CGFloat colors[] =
{
158 / 255.0, 149 / 255.0, 139 / 255.0, 1.00,
176 / 255.0, 163 / 255.0, 132 / 255.0, 1.00,
195 / 255.0, 172 / 255.0, 110 / 255.0, 1.00,
238 / 255.0, 206 / 255.0, 163 / 255.0, 1.00,
216 / 255.0, 188 / 255.0, 130 / 255.0, 1.00,
243 / 255.0, 210 / 255.0, 165 / 255.0, 1.00,
218 / 255.0, 186 / 255.0, 123 / 255.0, 1.00,
173 / 255.0, 156 / 255.0, 112 / 255.0, 1.00,
138 / 255.0, 120 / 255.0, 113 / 255.0, 1.00
};
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));(参数一为颜色空间,参数二为cgfloat颜色数组,参数三为各渐变颜色离中心的距离比,其值为0-1,参数四为有几组颜色(izeof(colors)/(sizeof(colors[0])*4)))

19.让启动界面图停留几秒
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[NSThread
sleepForTimeInterval:1];

self.window.rootViewController =
self.viewController;
[self.window
makeKeyAndVisible];
return
YES;
}
20.如何改变UITabBarController中tabBar和UINavigationController中navigationBar的颜色
self.tabBarController.tabBar.tintColor = [UIColor colorWithRed: green: blue:alpha: ];

homeViewController.navigationController.navigationBar.tintColor =[UIColorcolorWithRed:0.0/255.0green:205.0/255.0blue:205.0/255.0alpha:1.0];
21.UILabel自适应里面的文字,自动调整宽度和高度
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];这个frame是初设的,没关系,后面还会重新设置其size。
[label setNumberOfLines:0];
NSString *s = @"string......";
UIFont *font = [UIFont fontWithName:@"Arial" size:12];
CGSize size = CGSizeMake(320,2000);
CGSize labelsize = [s sizeWithFont:font constrainedToSize:sizelineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];
[self.view addSubView:label];
这样就可以对s赋值让其自动调整其大小了。

22.NSFileHandle文件读写类的使用
下面再来看一个读写文件的类NSFileHandle,其实它的实现就是调用c语言种文件流的操作。通过取得文件流的指针,然后定位指针的位置从而读取出文件中的内容,同样在文件中写入东西也是同样的道理,下面来看一小短代码。
NSFileHandle *TXTFileHandle;
NSString *szTXTFileTemp = @"111.txt";

TXTFileHandle = [NSFileHandlefileHandleForWritingAtPath:szTXTFileTemp];
//防止该文件不存在,如果不存在,新建该文件并写入空数据。

if(!TXTFileHandle)

{

[@""writeToFile:szTXTFileTemp atomically:NO encoding:1 error:nil];

TXTFileHandle = [NSFileHandlefileHandleForWritingAtPath:szTXTFileTemp];

}
[TXTFileHandle seekToEndOfFile];
char * conTemp = "mengtnt";
[TXTFileHandle writeData:[NSDatadataWithBytes:conTemp length:8];
[TXTFileHandle closeFile];
//下面是读取
TXTFileHandle = [NSFileHandlefileHandleForReadingAtPath:szTXTFileTemp];
NSData *fileData = [TXTFileHandlereadDataToEndOfFile];
NSlog(@"%@",[[NSStringalloc] initWithData:fileData encoding:NSUTF8StringEncoding]);
[TXTFileHandle closeFile];
23.获取沙河路径和改变当前路径
1.//参数NSDocumentDirectory要获取那种路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
2.//更改到待操作的目录下

[fileManager changeCurrentDirectoryPath:[documentsDirectorystringByExpandingTildeInPath]];
3.如果要指定其他文件目录,比如Caches目录,需要更换目录工厂常量,上面代码其他的可不变:
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory

, NSUserDomainMask

, YES);

使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。
4.常用路径工具函数
NSString * NSUserName();返回当前用户的登录名
NSString * NSFullUserName();返回当前用户的完整用户名
NSString * NSHomeDirectory();返回当前用户主目录的路径
NSString * NSHomeDirectoryForUser();返回用户user的主目录
NSString * NSTemporaryDirectory();返回可用于创建临时文件的路径目录

常用路径工具方法
-(NSString *) pathWithComponents:components
根据components(NSArray对象)中元素构造有效路径
-(NSArray *)pathComponents 析构路径,获取路径的各个部分
-(NSString *)lastPathComponent
提取路径的最后一个组成部分
-(NSString *)pathExtension
路径扩展名
-(NSString *)stringByAppendingPathComponent:path
将path添加到现有路径末尾
-(NSString *)stringByAppendingPathExtension:ext
将拓展名添加的路径最后一个组成部分
-(NSString *)stringByDeletingPathComponent
删除路径的最后一个部分
-(NSString *)stringByDeletingPathExtension
删除路径的最后一个部分的扩展名
-(NSString *)stringByExpandingTildeInPath
将路径中的代字符扩展成用户主目录(~)或指定用户主目录(~user)
-(NSString *)stringByResolvingSymlinksInPath
尝试解析路径中的符号链接
-(NSString *)stringByStandardizingPath
通过尝试解析~、..、.、和符号链接来标准化路径
-
使用路径NSPathUtilities.h
tempdir = NSTemporaryDirectory();
临时文件的目录名
path = [fm currentDirectoryPath];
[path lastPathComponent]; 从路径中提取最后一个文件名
fullpath = [path stringByAppendingPathComponent:fname];将文件名附加到路劲的末尾
extenson = [fullpath pathExtension];
路径名的文件扩展名
homedir = NSHomeDirectory();用户的主目录
component = [homedir pathComponents]; 路径的每个部分

NSProcessInfo类:允许你设置或检索正在运行的应用程序的各种类型信息
(NSProcessInfo*)processInfo 返回当前进程的信息
-(NSArray*)arguments
以NSString对象数字的形式返回当前进程的参数
-(NSDictionary *)environment
返回变量/值对词典。描述当前的环境变量
-(int)processIdentity 返回进程标识
-(NSString *)processName
返回进程名称
-(NSString *)globallyUniqueString
每次调用该方法都会返回不同的单值字符串,可以用这个字符串生成单值临时文件名
-(NSString *)hostname 返回主机系统的名称
-(unsigned int)operatingSystem
返回表示操作系统的数字
-(NSString *)operatingSystemName
返回操作系统名称
-(NSString *)operatingSystemVersionString
返回操作系统当前版本
-(void)setProcessName:(NSString*)name
将当前进程名称设置为name

============================================================================
NSFileHandle类允许更有效地使用文件。
可以实现如下功能
1、打开一个文件,执行读、写或更新(读写)操作;
2、在文件中查找指定位置;
3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中
另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。

一般而言,我们处理文件时都要经历以下三个步骤
1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。
2、对打开文件执行I/O操作。
3、关闭文件。
NSFileHandle*fileHandle
=[[NSFileHandle alloc]init];

fileHandle =[NSFileHandlefileHandleForReadingAtPath:path];//打开一个文件准备读取

fileHandle =[NSFileHandlefileHandleForWritingAtPath:path];

fileHandle =[NSFileHandlefileHandleForUpdatingAtPath:path];

fileData =[fileHandle availableData];//
从设备或者通道返回可用的数据

fileData =[fileHandlereadDataToEndOfFile];

[fileHandle writeData:fileData];//将NSData数据写入文件

[fileHandle closeFile];//关闭文件
基本文件操作NSFileHandle
常用NSFileHandle方法
(NSFileHandle*)fileHandleForReadingAtPath:path
打开一个文件准备读取
(NSFileHandle*)fileHandleForWritingAtPath:path
打开一个文件准备写入
(NSFileHandle*)fileHandleForUpdatingAtPath:path
打开一个文件准备更新(读取和写入)
-(NSData*)availableData 从设备或通道返回可用数据
-(NSData*)readDataToEndOfFile 读取其余的数据直到文件末尾(最多UINT_MAX字节)
-(NSData*)readDataOfLength:(unsignedint)bytes
从文件读取指定数目bytes的内容
-(void)writeData:data
将data写入文件
-(unsignedlong long) offsetInFile 获取当前文件的偏移量
-(void)seekToFileOffset:offset
设置当前文件的偏移量
-(unsignedlong long) seekToEndOfFile 将当前文件的偏移量定位的文件末尾
-(void)truncateFileAtOffset:offset
将文件的长度设置为offset字节
-(void)closeFile
关闭文件
... ...
NSString*file1=@"/Users/fhp/Desktop/1.txt";
NSString*file2=@"/users/fhp/Desktop/2.txt";

NSFileHandle*inFile=[NSFileHandle fileHandleForReadingAtPath:file1];
//打开1.txt
if(inFile==nil)
{
NSLog(@"打开1.txt错误");
return1;
}
// [[NSFileManagerdefaultManager] createFileAtPath:file2 contents:nil attributes:nil];
//创建文件2.txt
NSFileHandle*outFile=[NSFileHandle fileHandleForWritingAtPath:file2];
[outFile truncateFileAtOffset:0];
//清空内容,把指针指向开头
// [outFileseekToEndOfFile];
//可以把指针移动到文件结尾,这样就是增加文件内容,也可以seekTo到指定的位置

NSMutableData*buffer=[NSMutableData dataWithCapacity:2048];

while((buffer=[inFile readDataOfLength:2048])!=nil){
[outFile writeData:buffer];
//循环读取文件并写入
}

//当文件不大时,也可以用下面的方法,一次读入整个文件
//最多不超过UINT_MAX个字节,定义在limits.h中,一般为FFFFFFFF,即4GB
// NSData *buffer=[inFilereadDataToEndOfFile];
// //读取整个文件内容
// [outFilewriteData:buffer];
// //写入文件
[inFile closeFile];
[outFile closeFile];
//关闭文件
注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件。

24.过滤数组中的文件类型和获得文件属性
1. [fileListpathsMatchingExtensions:[NSArrayarrayWithObject:@"jpg"]];

2.NSDictionary * attributes = [filemanager attributesOfItemAtPath:[selfgetCompletePath] error:nil];
// file size

NSNumber *theFileSize;

if (theFileSize = [attributesobjectForKey:NSFileSize])
_fileSize= [theFileSizeintValue];
25.游戏截屏
CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];

[renderTexture begin];
[[self parent] visit];
[renderTexture end];
用这个截屏。用blur模糊。
26.运行无法选择模拟器
在targets--》summary--》iOSapplication target中的devices选项调一下就行(随便调),或者降低一下版本。

27.opencv改变像素点

CvScalar s;

for(int i = 0; i < target->height; i++)

{
for(int j = 0; j < target->width; j++)

{
s = cvGet2D(target, i, j); // to get the (i,j) pixel value

if(isNeedFix(s.val[0], s.val[1], s.val[2])) // to judge the pixel whether needs to fix

{
changePixelToBlue(s.val[0], s.val[1], s.val[2]); // fix pixel

cvSet2D(target,i,j,s); // to reset the (i,j) pixel value

}
}
}

28.nsvalue使用
1. 将NSRect放入NSArray中

NSRect rect = NSMakeRect(1, 2, 100, 200);

NSValue *rectValue = [NSValue valueWithBytes:&rect

objCType:@encode(NSRect)];

[array addObject:rectValue];

// 使用getValue提取数值

// 传递参数为要存储这个数值的变量的地址

rectValue = [array objectAtIndex: 0];

[rectValue getValue:&rect];
2. NSStringFromCGPoint(); CGPointFromString();
29.viewcontroller剖析
3. 主要属性
• view:控制器管理的根视图
• title:  控制器导航栏的标题
• wantsFullScreenLayout: 是否需要全屏显示
• interfaceOrientation: 界面方向
• navigationItem: 导航子项
• editing: 是否处理编辑状态
• hidesBottomBarWhenPushed: 入栈时隐藏底部栏
• toolbarItems: 工具栏子项集
• tabBarItem: 标签栏子项
• editButtonItem:返回一个编辑按钮
• parentViewController :交视图控制器
• searchDisplayController :搜索显示控制器
• splitViewController :分割视图控制器
• modalViewController :模式控制器
• navigationController :导航控制器
• tabBarController :标签控制器

4. 主要方法
• – loadView:不要主动调用该方法,当访问控制器view的时候,就会调用该方法。如果要自己创建view,则需要重写该方法。
• – viewDidLoad:当加载控制器的视图到内存时,该方法被调用。
• – viewWillAppear:
• – viewDidAppear:
• – viewWillDisappear:
• – viewDidDisappear:
• – shouldAutorotateToInterfaceOrientation:是否支持指定的界面方向。
• –willAnimateRotationToInterfaceOrientation:duration:将要使用动画过渡到某个界面方向。
• – didReceiveMemoryWarning:接收到内存警告信息。
• – presentModalViewController:animated:显示模式控制器
• – dismissModalViewControllerAnimated:隐藏模式控制器
• – setToolbarItems:animated:设置工具栏子项
• – setEditing:animated:设置编辑状态

1.iOS-UIImageView添加事件

UIView*view = [[UIControl alloc] initWithFrame:CGRectMake(50,200,150,150)];
view.backgroundColor = [UIColor clearColor];
[(UIControl *)view addTarget:self action:@selector(xxx)forControlEvents:UIControlEventTouchUpInside];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImageimageNamed:@"a.gif"]];
imageView.frame = CGRectMake(0, 0, view.bounds.size.width,view.bounds.size.height);
[view addSubview:imageView];
[imageView release];
[self.view addSubview:view];
[view release];

2.iOS-UITextView隐藏键盘

self._textView.delegate=self;
self._textView.returnKeyType=UIReturnKeyDone;
- (BOOL)textView:(UITextView *)textViewshouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]){
[textViewresignFirstResponder];
return NO;
}
return YES;
}

3.iOS-响应上下左右滑动手势

-(void)viewDidLoad{
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[[self
view] addGestureRecognizer:recognizer];
[recognizer release];
recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:self
action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[[self
view] addGestureRecognizer:recognizer];
[recognizer release];

recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
[[self
view] addGestureRecognizer:recognizer];
[recognizer release];

UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer
alloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
[[self
view] addGestureRecognizer:recognizer];
[recognizer release];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer{
if(recognizer.direction==UISwipeGestureRecognizerDirectionDown) {
NSLog(@"swipe down");
//执行程序
}
if(recognizer.direction==UISwipeGestureRecognizerDirectionUp) {
NSLog(@"swipe up");
//执行程序
}
if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
NSLog(@"swipe left");
//执行程序
}
if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
NSLog(@"swipe right");
//执行程序
}

}
4.ios-复制字符串到剪贴板

UIPasteboard *pasteboard = [UIPasteboard
generalPasteboard];
pasteboard.string =
self.label.text;

5.iOS-调用系统的短信和发送邮件功能,实现短信分享邮件分享

导入MessageUI.framework
.h文件中#import<MessageUI/MessageUI.h>
#import<MessageUI/MFMailComposeViewController.h>

实现 MFMailComposeViewControllerDelegate,
MFMessageComposeViewControllerDelegate

.m 文件
//邮件
-(void)showMailPicker{
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));

if (mailClass !=nil){
if ([mailClass
canSendMail]){
[selfdisplayMailComposerSheet];
}else{
UIAlertView *alert=[[UIAlertView
alloc]initWithTitle:@""message:@"设备不支持邮件功能"
delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
[alert release];
}
}else{

}

}
-(void)displayMailComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewControlleralloc]
init];

picker.mailComposeDelegate =self;

[pickersetSubject:@"文件分享"];

// Set up recipients
NSArray *toRecipients = [NSArrayarrayWithObject:@"first@qq.com"];
NSArray *ccRecipients = [NSArrayarrayWithObjects:@"second@qq.com",@"third@qq.com",
nil];
NSArray *bccRecipients = [NSArrayarrayWithObject:@"fourth@qq.com"];

[pickersetToRecipients:toRecipients];
[pickersetCcRecipients:ccRecipients];
[pickersetBccRecipients:bccRecipients];
//发送图片附件
//NSString *path =[[NSBundle mainBundle] pathForResource:@"rainy"ofType:@"jpg"];
//NSData *myData =[NSData dataWithContentsOfFile:path];
//[pickeraddAttachmentData:myData mimeType:@"image/jpeg"fileName:@"rainy.jpg"];

//发送txt文本附件
//NSString *path =[[NSBundle mainBundle] pathForResource:@"MyText"ofType:@"txt"];
//NSData *myData =[NSData dataWithContentsOfFile:path];
//[pickeraddAttachmentData:myData mimeType:@"text/txt"fileName:@"MyText.txt"];

//发送doc文本附件
//NSString *path =[[NSBundle mainBundle] pathForResource:@"MyText"ofType:@"doc"];
//NSData *myData =[NSData dataWithContentsOfFile:path];
//[pickeraddAttachmentData:myData mimeType:@"text/doc"fileName:@"MyText.doc"];

//发送pdf文档附件
/*
NSString *path = [[NSBundlemainBundle]
pathForResource:@"CodeSigningGuide"ofType:@"pdf"];
NSData *myData = [NSDatadataWithContentsOfFile:path];
[pickeraddAttachmentData:myData
mimeType:@"file/pdf"fileName:@"rainy.pdf"];
*/

// Fill out the emailbody text
NSString *emailBody =[NSStringstringWithFormat:@"我分享了文件给您,地址是%@",address]
;
[pickersetMessageBody:emailBodyisHTML:NO];

[selfpresentModalViewController:picker
animated:YES];
[pickerrelease];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)resulterror:(NSError*)error {

// Notifies users abouterrors associated with the interface
switch (result)
{
caseMFMailComposeResultCancelled:
NSLog(@"Result: Mail sending canceled");
break;
caseMFMailComposeResultSaved:
NSLog(@"Result: Mail saved");
break;
caseMFMailComposeResultSent:
NSLog(@"Result: Mail sent");
break;
caseMFMailComposeResultFailed:
NSLog(@"Result: Mail sending failed");
break;
default:
NSLog(@"Result: Mail not sent");
break;
}
[selfdismissModalViewControllerAnimated:YES];
}
//短信
-(void)showSMSPicker{
Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));

if(messageClass !=
nil) {
// Check whether thecurrent device is configured for sending SMS messages
if ([messageClass
canSendText]){
[selfdisplaySMSComposerSheet];
}
else {
UIAlertView *alert=[[UIAlertView
alloc]initWithTitle:@""message:@"设备不支持短信功能"
delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
[alert release];

}
}
else{
}
}
-(void)displaySMSComposerSheet
{
MFMessageComposeViewController *picker = [[MFMessageComposeViewControlleralloc]
init];
picker.messageComposeDelegate =self;
NSString *smsBody =[NSStringstringWithFormat:@"我分享了文件给您,地址是%@",address]
;
picker.body=smsBody;
[selfpresentModalViewController:picker
animated:YES];
[pickerrelease];
}

6.iOS-iphone自定义状态栏

-(void)setRefreshWindow{
CGRectframe =
CGRectMake(0.0,0.0,
320.0,20.0);
statusbarWindow= [[UIWindow
alloc]initWithFrame:frame];
[statusbarWindow
setBackgroundColor:[UIColor
clearColor]];
[statusbarWindow
setWindowLevel:UIWindowLevelStatusBar+1.0f];

// 添加自定义子视图
UIImageView*customView = [[UIImageView
alloc] initWithFrame:CGRectMake(100,0,
120, 18)];
customView.image=[UIImage
imageNamed:@"数据刷新栏.png"];

// UILabel*label=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 20)];
// // label.backgroundColor=[UIColor clearColor];
// label.text=@"数据正在刷新";
// [customView addSubview:label];
[statusbarWindowaddSubview:customView];
[statusbarWindow
makeKeyAndVisible];
}

7.ios-获取系统相簿里边的所有照片

#import <AssetsLibrary/AssetsLibrary.h>

-(void)getImgs{

dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool
alloc] init];

ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
NSLog(@"相册访问失败 =%@", [myerror
localizedDescription]);
if ([myerror.localizedDescriptionrangeOfString:@"Globaldenied access"].location!=NSNotFound)
{
NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
}else{
NSLog(@"相册访问失败.");
}
};

ALAssetsGroupEnumerationResultsBlockgroupEnumerAtion = ^(ALAsset *result,
NSUInteger index,
BOOL*stop){
if (result!=NULL){

if ([[result
valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto]){

NSString*urlstr=[NSString
stringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url
/*result.defaultRepresentation.fullScreenImage//图片的大图
result.thumbnail
//图片的缩略图小图
// NSRange range1=[urlstrrangeOfString:@"id="];
// NSString *resultName=[urlstrsubstringFromIndex:range1.location+3];
// resultName=[resultNamestringByReplacingOccurrencesOfString:@"&ext="withString:@"."];//格式demo:123456.png
*/

[self._dataArray addObject:urlstr];
}
}

};
ALAssetsLibraryGroupsEnumerationResultsBlock
libraryGroupsEnumeration = ^(ALAssetsGroup*group,
BOOL* stop){

if (group ==
nil)
{

}

if (group!=nil){
NSString *g=[NSString
stringWithFormat:@"%@",group];//获取相簿的组
NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos,Assets count:71

NSString *g1=[g
substringFromIndex:16] ;
NSArray *arr=[[NSArray
alloc] init];
arr=[g1 componentsSeparatedByString:@","];
NSString *g2=[[arr
objectAtIndex:0]substringFromIndex:5];
if ([g2
isEqualToString:@"CameraRoll"]) {
g2=@"相机胶卷";
}
NSString *groupName=g2;//组的name

[group enumerateAssetsUsingBlock:groupEnumerAtion];
}

};

ALAssetsLibrary* library = [[ALAssetsLibrary
alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:libraryGroupsEnumeration
failureBlock:failureblock];
[library release];

[pool release];
});

}

//------------------------根据图片的url反取图片-----

ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary
alloc] init];
NSURL *url=[NSURLURLWithString:urlStr];
[assetLibrary assetForURL:urlresultBlock:^(ALAsset*asset) {
UIImage *image=[UIImage
imageWithCGImage:asset.thumbnail];
cellImageView.image=image;

}failureBlock:^(NSError *error) {
NSLog(@"error=%@",error);
}
];

8.iOS-自定义修改拍照界面retake和use按钮

-(UIView*)findView:(UIView *)aView withName:(NSString *)name{
Classcl = [aView
class];
NSString*desc = [cl
description];

if([name
isEqualToString:desc])
return aView;

for(NSUInteger i =
0;i < [aView.subviews
count]; i++)
{
UIView *subView = [aView.subviewsobjectAtIndex:i];
subView = [self
findView:subViewwithName:name];
if (subView)
return subView;
}
return
nil;
}
-(void)addSomeElements:(UIViewController *)viewController{

UIView*PLCameraView=[self
findView:viewController.view
withName:@"PLCameraView"];
UIView*bottomBar=[self
findView:PLCameraViewwithName:@"PLCropOverlayBottomBar"];
UIImageView*bottomBarImageForSave = [bottomBar.subviewsobjectAtIndex:0];
UIButton*retakeButton=[bottomBarImageForSave.subviewsobjectAtIndex:0];
[retakeButtonsetTitle:@"重拍"
forState:UIControlStateNormal];
//左下角按钮
UIButton*useButton=[bottomBarImageForSave.subviews
objectAtIndex:1];
[useButton setTitle:@"上传"
forState:UIControlStateNormal];
//右下角按钮
}
- (void)navigationController:(UINavigationController *)navigationControllerwillShowViewController:(UIViewController*)viewController animated:(BOOL)animated{

[selfaddSomeElements:viewController];
}

9.iphone--字符串去除空格

NSCharacterSet *whitespace = [NSCharacterSet
whitespaceAndNewlineCharacterSet];
NSString* stringStr = [self.titleField.text
stringByTrimmingCharactersInSet:whitespace];

10.iphone-隐藏tabbar会出现空白,不能被其他view使用问题

- (void)hideTabBar:(BOOL) hidden{

[UIView
beginAnimations:nil
context:NULL];
[UIView
setAnimationDuration:0];

for(UIView *view
in self.tabBarController.view.subviews)
{
if([view
isKindOfClass:[UITabBar
class]])
{
if (hidden) {
[view setFrame:CGRectMake(view.frame.origin.x,
460, view.frame.size.width,view.frame.size.height)];
} else {
[view setFrame:CGRectMake(view.frame.origin.x,
460-49, view.frame.size.width, view.frame.size.height)];
}
}
else
{
if (hidden) {
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
view.frame.size.width,
460)];
} else {
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
view.frame.size.width,
460-49)];
}
}
}

[UIView
commitAnimations];
}

11.iOS-获取的NSDate date时间与实际相差8个小时解决方案

NSDate*date = [NSDate
date];
NSTimeZone *zone = [NSTimeZone
systemTimeZone];
NSIntegerinterval = [zone
secondsFromGMTForDate:date];
NSDate*localeDate = [date
dateByAddingTimeInterval:interval];

12.ios-拉伸图片变形解决办法:选取某一区域

UIImageView *fieldImage=[[UIImageView
alloc]initWithFrame:CGRectMake(37,
48+35,
240, 32)];
fieldImage.userInteractionEnabled=YES;
fieldImage.contentStretch=CGRectMake(0,
0.4, 1,
0.5);
fieldImage.image=[UIImage
imageNamed:@"输入框"];
[self.view
addSubview:fieldImage];

30.常量的定义,c,obj-c中是外连接的,c++中是内连接的。
Objective-C是标准C的另一种扩展,那么我犯的错误也就很明显了——当多个编译单元都引用那个define.h文件时出现了重复定义错。
今天来到机房一试,果然如此,只要将
const int NUMOFGHOST = 4;
改为
static const int NUMOFGHOST = 4;
就顺利编译通过了。这里的static是用来把定义的const常量标记为对外不可见的。
这里顺便抱怨一句:这xcode也太不人性化了,重复定义就说重复定义嘛,非要用红红的字标出来"Command/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failedwith exit code 1",反倒是很重要的那句"ld: duplicate symbol _NUMOFGHOST in /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/MazeView.oand/Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/pacManAppDelegate.o"用灰灰的颜色显示,也不懂得突出一下重点……

31.查看文件是什么框架的
lipo -info /path/to/your/library.a

32.改变alertview的高度
- (void)willPresentAlertView:(UIAlertView *)openURLAlert
{
// [openURLAlert setFrame:CGRectMake( 300,100, 300, 300 )];
[openURLAlertsetBounds:CGRectMake(-10, -80, 300, 300 )];
}

33.显示本地html文件

34.双击手势取消单击手势
[singleOnerequireGestureRecognizerToFail:doubleOne];
//防止:双击被单击拦截

35.获得系统语言
2012-05-07 21:18 19人阅读评论(0)
收藏举报
NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];
NSArray *languages = [defaultsobjectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
取得设置好的语言。。日语是ja,中文是zh_Hans

NSString*currentLanuage=[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];

36.获得设备方向
2012-04-15 10:48 220人阅读评论(0)
收藏举报
//获得设备方向
UIInterfaceOrientation orientation = [[UIApplicationsharedApplication]statusBarOrientation];

//程序启动时获取当前驱动的方向的方法
[[UIDevicecurrentDevice]beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientationcurrentOrientation = [ [UIDevicecurrentDevice]orientation];
//currentOrientation 可以获得UIDevice
正面向上向下方向
[[UIDevicecurrentDevice]endGeneratingDeviceOrientationNotifications];

37.去掉应用图标的高亮效果
1.内图标上部高亮效果的办法:

苹果默认会在 App Store
里的应用图标上半部自动添加高亮特效(如下图),虽是好心但有时候这半个光圈会破坏图标设计者的原作。如果您要去掉这一高亮特效,可以在程序的 info.plist
里添加一个值类型为 boolean
的字段:UIPrerenderedIcon,然后选中。

再上传应用,App Store
就不会在图标上添加高亮特效了。

iphone应用发布:如何去掉应用图标的高亮效果。

2.这需要在info.plist里面设置,Icon already includes gloss effects,Boolean类型,YES即可

38.实现震动效果
#import <AudioToolbox/AudioToolbox.h>
之后在方法里添加
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);就可以了

39.检查邮箱的正确性和是否为纯数字

+ (BOOL)validateEmail:(NSString *)str2validate

{
NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

NSPredicate *emailPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];

return [emailPredicate evaluateWithObject:str2validate];

}

+ (BOOL)validateNumeric:(NSString *)str2validate

{
NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];

NSRange range = [str2validate rangeOfCharacterFromSet:charSet];
return (range.location == NSNotFound) ? YES : NO;

}

40.textField的抖动

//TextField的晃动:Begin

@interface UITextField(shake)

- (void)shake;

@end

@implementation UITextField(shake)

- (void)shake

{
CAKeyframeAnimation *animationKey = [CAKeyframeAnimationanimationWithKeyPath:@"position"];

[animationKey setDuration:0.5f];

NSArray *array = [[NSArrayalloc] initWithObjects:
[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],

[NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],

nil];
[animationKey setValues:array];
[array release];

NSArray *times = [[NSArrayalloc] initWithObjects:

[NSNumbernumberWithFloat:0.1f],
[NSNumbernumberWithFloat:0.2f],

[NSNumbernumberWithFloat:0.3f],
[NSNumbernumberWithFloat:0.4f],

[NSNumbernumberWithFloat:0.5f],
[NSNumbernumberWithFloat:0.6f],

[NSNumbernumberWithFloat:0.7f],
[NSNumbernumberWithFloat:0.8f],

[NSNumbernumberWithFloat:0.9f],
[NSNumbernumberWithFloat:1.0f],

nil];
[animationKey setKeyTimes:times];
[times release];

[self.layeraddAnimation:animationKey forKey:@"TextFieldShake"];

}

@end
//TextField的晃动:End

41.UIButton去除按下时的状态
btn2.adjustsImageWhenHighlighted = NO;

42.获得设备的电量
[[UIDevicecurrentDevice] setBatteryMonitoringEnabled:YES];

if([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) {
NSLog(@"Device is charging.");
}

43.退出程序
- (void)animationFinished:(NSString *)animationIDfinished:(NSNumber *)finished context:(void *)context
{
if ([animationID
compare:@"exitApplication"] ==
0)
{
exit(0);
}
}

- (void)exitApplication
{
UIWindow *window = [[UIApplication
sharedApplication]
keyWindow];

[UIView
beginAnimations:@"exitApplication"
context:nil];
[UIView
setAnimationDuration:0.75];
[UIView
setAnimationDelegate:self];
[UIView
setAnimationTransition:UIViewAnimationTransitionCurlDown
forView:window cache:NO];
[UIViewsetAnimationDidStopSelector:@selector(animationFinished: finished: context:)];
window.bounds =
CGRectMake(512,
384, 0, 0);
[UIView
commitAnimations];
}

44.画文字

//设置画笔线条粗细

CGContextSetLineWidth(context, 1.0);
//设置矩形填充颜色:红色

CGContextSetRGBFillColor (context, 1.0, 0.0, 0.0, 1.0);

//设置字体

UIFont *font = [UIFont boldSystemFontOfSize:31.0];

//在指定的矩形区域内画文字

[text drawInRect:rect withFont:font];

45.itunes图标
要加itunes图标就把图标去掉扩展名,改名为iTunesArtwork扔到资源目录下

46.两个应用之间传递信息
第一步:
在目标程序(通过订制的url开打的程序)中,设置订制的url,订制方法如下:
打开plist文件添加一个键值对URL types,并设置成如下形式:

其中图中的JJMFAPP就是你自己定义的url协议(名字随别取,最好和应用程序有关联的名字,之后将会用到它)

第二步:
在其它的应用中打开第一步中的应用,如下:(看见"JJMFAPP:"没,这个就是第一步设置的url协议)
NSURL *jjmfURL = [NSURLURLWithString:@"JJMFAPP:"];
if ([[UIApplication
sharedApplication]
canOpenURL:jjmfURL])
{
[[UIApplication
sharedApplication] openURL:jjmfURL];
}

如果要传递参数则如下:(规则是 开头必须是订制的url协议如:JJMFAPP:,随后跟参数,参数之间用&隔开)
NSString *dataToPath = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];
int updataID = [usersDefaultintegerForKey:@"JJMFAPP"];
NSString *informationString = [NSString
stringWithFormat:@"JJMFAPP:message=%@&updataID=%d",dataToPath,updataID];
informationString = [informationString
stringByReplacingOccurrencesOfString:@" "
withString:@"%20"];
NSURL *updataURL = [NSURLURLWithString:informationString];
// NSLog(@"%@",updataURL);
if ([[UIApplicationsharedApplication]
canOpenURL:updataURL])
{
[[UIApplication
sharedApplication] openURL:updataURL];
}

第三步:
在目标程序中解析订制的url并打开程序(必须实现UIApplicationDelegate协议,并实现
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL *)url
方法),如下:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
if(url ==
nil)
{
return
NO;
}

NSString*URLString = [url
absoluteString];
if(![URLString
hasPrefix:@"JJMFAPP:"])
{
return
NO;
}

// URLString= [URLString substringFromIndex:[URLStringrangeOfString:@"UPDATAJJMF:message="].location+19];
NSMutableCharacterSet *set = [[NSMutableCharacterSet
alloc] init];
[set addCharactersInString:@"&="];
NSArray *pathArray = [URLString
componentsSeparatedByCharactersInSet:set];
[set release];
URLString =[pathArray objectAtIndex:1];
Arguments2App *arg2app = [Arguments2App
sharedArguments];
arg2app.groupid = [[pathArray
objectAtIndex:3]
intValue];
[arg2app writeToUserDefaults];

URLString =[URLString stringByReplacingOccurrencesOfString:@"%20"
withString:@" "];
BOOLpathExists;
BOOLyes = [[NSFileManager
defaultManager] fileExistsAtPath:URLStringisDirectory:&pathExists];
if(yes && pathExists)
{
self.viewController.upToPath = URLString;

NSUserDefaults *usersDefault = [NSUserDefaults
standardUserDefaults];
[usersDefault setObject:URLString
forKey:@"UPDATATOPATH"];
[usersDefault synchronize];
}
else
{
self.viewController.upToPath =
nil;
}

return
YES;
}

在 - (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions 此方法中也可以得到订制的url信息
{//处理应用程序间信息共享
NSString *sourceApp =[launchOptions
objectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
NSURL *url = [launchOptions
objectForKey:UIApplicationLaunchOptionsURLKey];
NSString *msg = [NSStringstringWithFormat:@"sourceApp:%@,url:%@",sourceApp,url];
UIAlertView *alert = [[UIAlertViewalloc]
initWithTitle:NSLocalizedString(@"test message",
nil)
message:msg
delegate:self
cancelButtonTitle:nilotherButtonTitles:@"OK",nil];
[alert show];
[alert release];
}

47.icon总结
Icon-72.png
Icon-Small-50.png
Icon-Small.png
Icon-Small@2x.png
Icon.png
Icon@2x.png
iTunesArtwork
Default.png
Default@2x.png
Default-Portrait.png
Default-Landscape.png

48.将秒(UNIX时间截)转为标准时间:时间截的长度不能超过10位,应该是除以9999999999取余
简单的来说“1327670455”表示从1970年1月1日0点0分0秒到现在为止经过了1327670455秒
-(NSString*)dateInFormat:(time_t)dateTime format:(NSString*) stringFormat
{
char buffer[80];
const char *format =[stringFormat UTF8String];
struct tm * timeinfo;
timeinfo =localtime(&dateTime);
strftime(buffer, 80,format, timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}
//NSString *str =@"%d.%m.%Y %H:%M:%S";
NSString *str =@"%Y-%m-%d %H:%M:%S";
NSString *time = [selfdateInFormat:1353635983563 format:str];
NSLog(@"createdAt:%@",time);

49.数组排序
1.第一种方法
NSSortDescriptor *sorts;
switch (segment.selectedSegmentIndex)
{
case 0:
sorts = [[NSSortDescriptor
alloc] initWithKey:
@"subject" ascending:
YES];
break;
case 1:
sorts = [[NSSortDescriptor
alloc] initWithKey:
@"priority" ascending:
YES];
break;
case 2:
default:
sorts = [[NSSortDescriptor
alloc] initWithKey:
@"date" ascending:
YES];
break;
};
NSArray *arr = [NSArray
arrayWithObject: sorts];
[tododb.todolist.todoarray
sortUsingDescriptors: arr];

2.第二种方法
//字典的keys数组,按从小到大的顺序排列
keysArray = [[[productDic
allKeys] sortedArrayUsingComparator:^(id obj1,
id obj2){
if ([obj1
integerValue]> [obj2 integerValue])
{
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1
integerValue]< [obj2 integerValue])
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}] retain];

50.日期装换成字符串
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
NSLocale *locale =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
[dateFormattersetLocale:locale];//location设置为中国
[locale release];
[dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss EEEE"];

todayDate = [NSDatedate];

dateLabel.text =[dateFormatter stringFromDate:todayDate];

51.摆动动画
1.
//添加登陆界面
- (void)addLandingView
{//添加登陆界面
matView = [[UIView
alloc] initWithFrame:CGRectMake(0, 0, 1024, 748)];
matView.backgroundColor = [UIColor
clearColor];
[self.view
addSubview:matView];
[matView
release];

JJMFLandingView *landingView = [[JJMFLandingView
alloc] initWithFrame:CGRectMake(0, 0, 500, 240)];
landingView.center =
CGPointMake(512,274);
landingView.deleget =
self;
[self.view
addSubview:landingView];
[landingView release];

CAKeyframeAnimation *animationKey = [CAKeyframeAnimation
animationWithKeyPath:@"position"];
[animationKey setDuration:1.f];
NSArray *array = [[NSArray
alloc] initWithObjects:
[NSValuevalueWithCGPoint:CGPointMake(512,-120)],
[NSValuevalueWithCGPoint:CGPointMake(512,274)],
[NSValuevalueWithCGPoint:CGPointMake(512,204)],
[NSValuevalueWithCGPoint:CGPointMake(512,274)],
[NSValuevalueWithCGPoint:CGPointMake(512,244)],
[NSValuevalueWithCGPoint:CGPointMake(512,274)],
nil];
[animationKey setValues:array];
[array release];

NSArray *times = [[NSArray
alloc] initWithObjects:
[NSNumbernumberWithFloat:0.1f],
[NSNumbernumberWithFloat:0.25f],
[NSNumbernumberWithFloat:0.4f],
[NSNumbernumberWithFloat:0.6f],
[NSNumbernumberWithFloat:0.8f],
[NSNumbernumberWithFloat:1.0f],
nil];
[animationKey setKeyTimes:times];
[times release];

[landingView.layer
addAnimation:animationKeyforKey:@"showLandView"];
}

2.

/*

* pointToAngle 按角度旋转
* @angel CGFloat 角度

* @duration CGFloat 动画执行时间

*/

- (void) pointToAngle:(CGFloat) angle Duration:(CGFloat) duration

{
CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"transform"];

NSMutableArray *values=[NSMutableArray array];

anim.duration = duration;
anim.autoreverses = NO;
anim.fillMode = kCAFillModeForwards;
anim.removedOnCompletion= NO;

CGFloat distance = angle/10;
//设置转动路径,不能直接用 CABaseAnimation 的toValue,那样是按最短路径的,转动超过180度时无法控制方向

int i = 1;

for(;i<=10;i++){
[values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*i)], 0, 0, 1)]];

}
//添加缓动效果

[values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i))], 0, 0, 1)]];

[values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-2))], 0, 0, 1)]];

[values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-1))], 0, 0, 1)]];

anim.values=values; ;
[pointer.layer addAnimation:anim forKey:@"cubeIn"];

gaugeAngle = gaugeAngle+angle;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: