iOS 小记(1)

来源:互联网 发布:柊筱娅cos淘宝 编辑:程序博客网 时间:2024/05/20 18:00

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; 

    CGColorSpaceRef colorSpace = 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); 

    return grayImage; 

}

其中,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); 

     

    [image drawAtPoint: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 outside the view");
    }

    else 

    {
        UIView *hitView=[self hitTest:[[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:在窗口的最底层添加一个320480UIControl控件:


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改成Done textField.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:UIKeyboardDidShowNotification object:nil];

 

   [[NSNotificationCenter defaultCenter] addObserver:self

           selector:@selector(keyboardWasHidden:)

           name:UIKeyboardDidHideNotification object: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 = [info objectForKey:UIKeyboardBoundsUserInfoKey];

   CGSize keyboardSize = [aValue CGRectValue].size;

 

   // Resize the scroll view (which is the root view 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:textFieldRect animated:YES];

 

   keyboardShown = YES;

}

 

 

// Called when theUIKeyboardDidHideNotification is sent

-(void)keyboardWasHidden:(NSNotification*)aNotification

{

   NSDictionary* info = [aNotification userInfo];

 

   // Get the size of the keyboard.

   NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];

   CGSize keyboardSize = [aValue CGRectValue].size;

 

   // Reset the height of the scroll view to its original value

   CGRect viewFrame = [scrollView frame];

   viewFrame.size.height += keyboardSize.height;

   scrollView.frame = viewFrame;

 

   keyboardShown = NO;

}


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


7.隐藏状态栏

隐藏状态栏:

[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]


横屏:

[[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

orientation == UIInterfaceOrientationLandscapeLeft

window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds];全屏


自动适应父视图大小:

aView.autoresizingSubviews = YES;

aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);


8.释放webview缓存

NSURLCache *sharedCache= [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];

[NSURLCache setSharedURLCache:sharedCache];


//Clear All Cookies

for(NSHTTPCookie*cookie in [[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代码  

  1. NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  
  2. // app名称  
  3. NSString *name = [infoDictionary objectForKey:@"CFBundleDisplayName"];  
  4. // app版本  
  5. NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  
  6. // app build版本  
  7. NSString *build = [infoDictionary objectForKey:@"CFBundleVersion"];  

 

UILabel根据text自动调整大小

 

C代码  

  1. label.text = @"**********";  
  2. CGRect frame = label.frame;  
  3. frame.size.height = 10000;  // 设置一个很大的高度  
  4. label.frame = frame;  
  5. [label sizeToFit];  
  6. frame.size.height = label.frame.size.height;  
  7. label.frame = frame;  

 

直接拨打有分机号的电话


C代码  

  1. [[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.应用图标右上角的提示小红圈的实现

[[UIApplication sharedApplication]setApplicationIconBadgeNumber:2];

15.一个问题关于清除本地推送数据 local notification

通过服务器推送时,进入游戏,通知中心会清除掉数据。

但是本地推送我通过通知中心点进来,通知中心中还继续显示N多条信息,有清除方法吗?

[[UIApplication sharedApplication] scheduledLocalNotifications].count 0 因为都已经推送出去了。


最佳答案

[UIApplication sharedApplication] cancelAllLocalNotifications];

16.local notification在具体时间推送的问题

代码贴上来

    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.iphone no architectures to compile for (arches = i386,valid_archs = armv6 armv7)错误解决办法

在targets--->Bulid Settings选项下面的Architectures一栏里,在Valid Architectures里加入一项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.

    [NSThreadsleepForTimeInterval:1];

    

    self.window.rootViewController =self.viewController;

    [self.windowmakeKeyAndVisible];

    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:size lineBreakMode: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 = [NSFileHandle fileHandleForWritingAtPath:szTXTFileTemp];

    //防止该文件不存在,如果不存在,新建该文件并写入空数据。
    if(!TXTFileHandle)
    {
        [@"" writeToFile:szTXTFileTemp atomically:NO encoding:1 error:nil];
        TXTFileHandle = [NSFileHandle fileHandleForWritingAtPath:szTXTFileTemp];
    }

    [TXTFileHandle seekToEndOfFile];

    char * conTemp = "mengtnt";

    [TXTFileHandle  writeData:[NSData dataWithBytes:conTemp length:8];

    [TXTFileHandle closeFile];

    //下面是读取

    TXTFileHandle = [NSFileHandle fileHandleForReadingAtPath:szTXTFileTemp];

    NSData *fileData = [TXTFileHandle readDataToEndOfFile];

    NSlog(@"%@",[[NSString alloc] initWithData:fileData  encoding:NSUTF8StringEncoding]);

    [TXTFileHandle closeFile];

23.获取沙河路径和改变当前路径

1.//参数NSDocumentDirectory要获取那种路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径

2.//更改到待操作的目录下
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];

3.如果要指定其他文件目录,比如Caches目录,需要更换目录工厂常量,上面代码其他的可不变:

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

 

使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。

4.常用路径工具函数

NSString * NSUserName(); 返回当前用户的登录名 

NSString * NSFullUserName(); 返回当前用户的完整用户名 

NSString * NSHomeDirectory(); 返回当前用户主目录的路径 

NSString * NSHomeDirectoryForUser();返回用户user的主目录 

NSString * NSTemporaryDirectory();返回可用于创建临时文件的路径目录 


常用路径工具方法

-NSString * pathWithComponentscomponents   根据componentsNSArray对象)中元素构造有效路径 

-NSArray *pathComponents                                          析构路径,获取路径的各个部分 

-NSString *lastPathComponent                                      提取路径的最后一个组成部分 

-NSString *pathExtension                                          路径扩展名 

-NSString *stringByAppendingPathComponentpath                    path添加到现有路径末尾 

-NSString *stringByAppendingPathExtensionext          将拓展名添加的路径最后一个组成部分 

-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                                  返回变量/值对词典。描述当前的环境变量

-intprocessIdentity                                          返回进程标识

-NSString *processName                                      返回进程名称

-NSString *globallyUniqueString  每次调用该方法都会返回不同的单值字符串,可以用这个字符串生成单值临时文件名   

-NSString *hostname                                          返回主机系统的名称 

-unsigned intoperatingSystem                                返回表示操作系统的数字 

-NSString *operatingSystemName                                    返回操作系统名称 

-NSString *operatingSystemVersionString                                    返回操作系统当前版本

-voidsetProcessName:(NSString *name                                将当前进程名称设置为name 


============================================================================

 NSFileHandle类允许更有效地使用文件。

可以实现如下功能

1、打开一个文件,执行读、写或更新(读写)操作;

2、在文件中查找指定位置;

3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中

另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。


一般而言,我们处理文件时都要经历以下三个步骤

1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。

2、对打开文件执行I/O操作。

3、关闭文件。

NSFileHandle*fileHandle=[[NSFileHandle alloc]init];
fileHandle =[NSFileHandle fileHandleForReadingAtPath:path];//打开一个文件准备读取
fileHandle =[NSFileHandle fileHandleForWritingAtPath:path];
fileHandle =[NSFileHandle fileHandleForUpdatingAtPath:path];
fileData =[fileHandle availableData];//从设备或者通道返回可用的数据
fileData =[fileHandle readDataToEndOfFile];
[fileHandle writeData:fileData];//NSData数据写入文件
[fileHandle closeFile];//关闭文件

基本文件操作NSFileHandle

常用NSFileHandle方法

NSFileHandle *fileHandleForReadingAtPathpath                        打开一个文件准备读取

NSFileHandle *fileHandleForWritingAtPathpath                        打开一个文件准备写入

NSFileHandle *fileHandleForUpdatingAtPathpath                        打开一个文件准备更新(读取和写入)

-NSData *availableData                                                  从设备或通道返回可用数据

-NSData *readDataToEndOfFile                                            读取其余的数据直到文件末尾(最多UINT_MAX字节)

-NSData *readDataOfLength:(unsigned intbytes从文件读取指定数目bytes的内容

-voidwriteDatadata                  data写入文件

-unsigned long long offsetInFile      获取当前文件的偏移量

-voidseekToFileOffsetoffset        设置当前文件的偏移量 

-unsigned long long seekToEndOfFile      将当前文件的偏移量定位的文件末尾

-voidtruncateFileAtOffsetoffset        将文件的长度设置为offset字节

-voidcloseFile                          关闭文件

... ...

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;

}

// [[NSFileManager defaultManager] createFileAtPath:file2 contents:nil attributes:nil];

//创建文件 2.txt

NSFileHandle*outFile=[NSFileHandle fileHandleForWritingAtPath:file2];

[outFile truncateFileAtOffset:0];

//清空内容,把指针指向开头

// [outFile seekToEndOfFile];

//可以把指针移动到文件结尾,这样就是增加文件内容,也可以seekTo到指定的位置

 

 

 

NSMutableData*buffer=[NSMutableData dataWithCapacity:2048];

 

while ((buffer=[inFile readDataOfLength:2048])!=nil){

[outFile writeData:buffer];

//循环读取文件并写入

}

 

 

//当文件不大时,也可以用下面的方法,一次读入整个文件

//最多不超过UINT_MAX个字节,定义在limits.h中,一般为FFFFFFFF,4GB

// NSData *buffer=[inFile readDataToEndOfFile];

// //读取整个文件内容

// [outFile writeData:buffer];

// //写入文件

[inFile closeFile];

[outFile closeFile];

//关闭文件

注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件。


24.过滤数组中的文件类型和获得文件属性 

1. [fileList pathsMatchingExtensions:[NSArrayarrayWithObject:@"jpg"]];


2.NSDictionary * attributes = [filemanager attributesOfItemAtPath:[self getCompletePath] error:nil];

// file size
     NSNumber *theFileSize;
     if (theFileSize = [attributes objectForKey:NSFileSize])

       _fileSize= [theFileSize intValue];

25.游戏截屏

CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];

    

    [renderTexture begin];

    [[self parent] visit];

    [renderTexture end];

用这个截屏。用blur模糊。


26.运行无法选择模拟器

        在targets--》summary--》iOS application target中的devices选项调一下就行(随便调),或者降低一下版本。



27.opencv改变像素点

  1. CvScalar s;  
  2.   
  3.         for(int i = 0; i < target->height; i++)  
  4.         {  
  5.             for(int j = 0; j < target->width; j++)  
  6.             {  
  7.                 s = cvGet2D(target, i, j); // to get the (i,j) pixel value  
  8.                 if(isNeedFix(s.val[0], s.val[1], s.val[2])) // to judge the pixel whether needs to fix   
  9.                 {  
  10.                     changePixelToBlue(s.val[0], s.val[1], s.val[2]); // fix pixel  
  11.                     cvSet2D(target,i,j,s); // to reset the (i,j) pixel value  
  12.                 }  
  13.             }  
  14.         }


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.iOSUIImageView添加事件


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:[UIImage imageNamed:@"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.iOSUITextView隐藏键盘


self._textView.delegate=self;

self._textView.returnKeyType=UIReturnKeyDone;

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text {

    if ([text isEqualToString:@"\n"]) {

        [textView resignFirstResponder];

        return NO;

    }

    return YES;

}


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


-(void)viewDidLoad{

UISwipeGestureRecognizer *recognizer; 

recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];

     [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];

    [[selfview] addGestureRecognizer:recognizer];

[recognizer release];

    recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];

     [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];

    [[selfview] addGestureRecognizer:recognizer];

[recognizer release];


recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];

     [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];

    [[selfview] addGestureRecognizer:recognizer];

[recognizer release];


UISwipeGestureRecognizer *recognizer;

    recognizer = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleSwipeFrom:)];

     [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];

    [[selfview] 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 = [UIPasteboardgeneralPasteboard];

    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];

            [alertshow];

            [alertrelease];

        }

    }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];

//[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy.jpg"];


//发送txt文本附件

//NSString *path = [[NSBundle mainBundle] pathForResource:@"MyText" ofType:@"txt"];

//NSData *myData = [NSData dataWithContentsOfFile:path];

//[picker addAttachmentData:myData mimeType:@"text/txt" fileName:@"MyText.txt"];


//发送doc文本附件 

//NSString *path = [[NSBundle mainBundle] pathForResource:@"MyText" ofType:@"doc"];

//NSData *myData = [NSData dataWithContentsOfFile:path];

//[picker addAttachmentData:myData mimeType:@"text/doc" fileName:@"MyText.doc"];


//发送pdf文档附件

/*

NSString *path = [[NSBundlemainBundle]pathForResource:@"CodeSigningGuide"ofType:@"pdf"];

NSData *myData = [NSDatadataWithContentsOfFile:path];

[pickeraddAttachmentData:myDatamimeType:@"file/pdf"fileName:@"rainy.pdf"];

*/



// Fill out the email body text

NSString *emailBody =[NSStringstringWithFormat:@"我分享了文件给您,地址是%@",address] ;

[pickersetMessageBody:emailBodyisHTML:NO];


[selfpresentModalViewController:pickeranimated:YES];

[pickerrelease];

}

- (void)mailComposeController:(MFMailComposeViewController*)controller 

          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {



// Notifies users about errors 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 the current device is configured for sending SMS messages

        if ([messageClass canSendText]) {

        [selfdisplaySMSComposerSheet];

        }

        else

            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@""message:@"设备不支持短信功能" delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:nil];

            [alertshow];

            [alertrelease];

            

        }

    }

    else {

        }

 }

-(void)displaySMSComposerSheet

{

   MFMessageComposeViewController *picker = [[MFMessageComposeViewControlleralloc]init];

picker.messageComposeDelegate =self;

NSString *smsBody =[NSStringstringWithFormat:@"我分享了文件给您,地址是%@",address] ;

    picker.body=smsBody;

[selfpresentModalViewController:pickeranimated:YES];

[pickerrelease];

}


6.iOSiphone自定义状态栏


-(void)setRefreshWindow{

    CGRect frame = CGRectMake(0.0,0.0, 320.0,20.0);

    statusbarWindow = [[UIWindow alloc] initWithFrame:frame];

    [statusbarWindowsetBackgroundColor:[UIColorclearColor]];

    [statusbarWindowsetWindowLevel:UIWindowLevelStatusBar+1.0f];

    

    //添加自定义子视图

    UIImageView *customView = [[UIImageViewalloc] initWithFrame:CGRectMake(100,0, 120, 18)];

    customView.image=[UIImageimageNamed:@"数据刷新栏.png"];

    

//    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 20)];

//    //    label.backgroundColor=[UIColor clearColor];

//    label.text=@"数据正在刷新";

//    [customView addSubview:label];

    [statusbarWindowaddSubview:customView];

    [statusbarWindowmakeKeyAndVisible];

}


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


#import <AssetsLibrary/AssetsLibrary.h>



-(void)getImgs{

    

    dispatch_async(dispatch_get_main_queue(), ^{

        NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init];

        

        

        ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){

            NSLog(@"相册访问失败 =%@", [myerrorlocalizedDescription]);

            if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {

                  NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");

            }else{

                NSLog(@"相册访问失败.");

            }

        };

        

        ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop){

            if (result!=NULL) {

        

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

                    

                   NSString *urlstr=[NSStringstringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url

/*result.defaultRepresentation.fullScreenImage//图片的大图

result.thumbnail                             //图片的缩略图小图

//                    NSRange range1=[urlstr rangeOfString:@"id="];

//                    NSString *resultName=[urlstr substringFromIndex:range1.location+3];

//                    resultName=[resultName stringByReplacingOccurrencesOfString:@"&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=[g1componentsSeparatedByString:@","];

                NSString *g2=[[arr objectAtIndex:0]substringFromIndex:5];

                if ([g2 isEqualToString:@"Camera Roll"]) {

                    g2=@"相机胶卷";

                }

                NSString *groupName=g2;//组的name

                

                [groupenumerateAssetsUsingBlock:groupEnumerAtion];

            }

            

        };

        

        ALAssetsLibrary* library = [[ALAssetsLibraryalloc] init];

        [library enumerateGroupsWithTypes:ALAssetsGroupAll

                              usingBlock:libraryGroupsEnumeration 

                            failureBlock:failureblock];

        [library release];      


        [pool release];

    });  

    

}


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


  ALAssetsLibrary *assetLibrary=[[ALAssetsLibraryalloc] init]; 

NSURL *url=[NSURLURLWithString:urlStr];

[assetLibrary assetForURL:url resultBlock:^(ALAsset *asset)  {

                UIImage *image=[UIImage imageWithCGImage:asset.thumbnail];

                cellImageView.image=image;

           

                }failureBlock:^(NSError *error) {

                   NSLog(@"error=%@",error);

            }

             ];


8.iOS-自定义修改拍照界面retakeuse按钮


-(UIView *)findView:(UIView *)aView withName:(NSString *)name{  

    Class cl = [aView class];  

    NSString *desc = [cl description];  

    

    if ([name isEqualToString:desc])  

        return aView;  

    

    for (NSUInteger i = 0; i < [aView.subviews count]; i++)  

    {  

        UIView *subView = [aView.subviews objectAtIndex:i];  

        subView = [selffindView:subView withName:name];  

        if (subView)  

            return subView;  

    }  

    return nil;  

-(void)addSomeElements:(UIViewController *)viewController{


    

    UIView *PLCameraView=[self findView:viewController.view withName:@"PLCameraView"];

    UIView *bottomBar=[self findView:PLCameraView withName:@"PLCropOverlayBottomBar"];

    UIImageView *bottomBarImageForSave = [bottomBar.subviewsobjectAtIndex:0];

    UIButton *retakeButton=[bottomBarImageForSave.subviewsobjectAtIndex:0];  

    [retakeButton setTitle:@"重拍"forState:UIControlStateNormal]; //左下角按钮

    UIButton *useButton=[bottomBarImageForSave.subviewsobjectAtIndex:1];  

    [useButton setTitle:@"上传"forState:UIControlStateNormal]; //右下角按钮

}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{

  

    [selfaddSomeElements:viewController];

}


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


 NSCharacterSet *whitespace = [NSCharacterSetwhitespaceAndNewlineCharacterSet];

  NSString * stringStr = [self.titleField.textstringByTrimmingCharactersInSet:whitespace];


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


- (void) hideTabBar:(BOOL) hidden{

    

    [UIViewbeginAnimations:nilcontext:NULL];

    [UIViewsetAnimationDuration:0];

     

    for(UIView *view in self.tabBarController.view.subviews)

    {

        if([view isKindOfClass:[UITabBarclass]])

        {

            if (hidden) {

                [viewsetFrame:CGRectMake(view.frame.origin.x,460, view.frame.size.width, view.frame.size.height)];

            } else {

                [viewsetFrame:CGRectMake(view.frame.origin.x,460-49, view.frame.size.width, view.frame.size.height)];

            }

        } 

        else 

        {

            if (hidden) {

                [viewsetFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width,460)];

            } else {

                [viewsetFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width,460-49)];

            }

        }

    }

    

    [UIViewcommitAnimations];

}


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


 NSDate *date = [NSDatedate];

    NSTimeZone *zone = [NSTimeZonesystemTimeZone];

    NSInteger interval = [zone secondsFromGMTForDate: date];

    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];


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


 UIImageView *fieldImage=[[UIImageViewalloc]initWithFrame:CGRectMake(37,48+35,240, 32)];

    fieldImage.userInteractionEnabled=YES;

    fieldImage.contentStretch=CGRectMake(0,0.4, 1, 0.5);

    fieldImage.image=[UIImageimageNamed:@"输入框"];

    [self.viewaddSubview: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 failed with exit code 1",反倒是很重要的那句"ld: duplicate symbol _NUMOFGHOST in /Users/asfgasiyf/Desktop/pacMan/build/pacMan.build/Debug-iphonesimulator/pacMan.build/Objects-normal/i386/MazeView.o and /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 )];

    [openURLAlert setBounds:CGRectMake(-10, -80, 300, 300 )];

}


33.显示本地html文件

07G8]~Q5A}OIHXL4`U)UX81.jpg

34.双击手势取消单击手势

[singleOne requireGestureRecognizerToFail:doubleOne]; //防止:双击被单击拦截


35.获得系统语言

2012-05-07 21:18 19人阅读 评论(0) 收藏举报

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

NSArray *languages = [defaults objectForKey:@"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];

   UIDeviceOrientation currentOrientation = [ [UIDevicecurrentDevice]orientation];

    //currentOrientation可以获得UIDevice正面向上向下方向

    [[UIDevicecurrentDevice]endGeneratingDeviceOrientationNotifications];


37.去掉应用图标的高亮效果

1.内图标上部高亮效果的办法:


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

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


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

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


38.实现震动效果

#import <AudioToolbox/AudioToolbox.h>

之后在方法里添加

AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);就可以了


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

  1. + (BOOL)validateEmail:(NSString *)str2validate  
  2. {  
  3.     NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
  4.     NSPredicate *emailPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];  
  5.       
  6.     return [emailPredicate evaluateWithObject:str2validate];  


  1. + (BOOL)validateNumeric:(NSString *)str2validate  
  2. {  
  3.     NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];  
  4.     NSRange range = [str2validate rangeOfCharacterFromSet:charSet];  
  5.     return (range.location == NSNotFound) ? YES : NO;  


40.textField的抖动

  1. //TextField的晃动:Begin  
  2. @interface UITextField(shake)  
  3.   
  4. - (void)shake;  
  5.   
  6. @end  
  7.   
  8. @implementation UITextField(shake)  
  9.   
  10. - (void)shake  
  11. {  
  12.     CAKeyframeAnimation *animationKey = [CAKeyframeAnimationanimationWithKeyPath:@"position"];  
  13.     [animationKey setDuration:0.5f];  
  14.       
  15.     NSArray *array = [[NSArrayalloc] initWithObjects:  
  16.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
  17.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
  18.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
  19.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
  20.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
  21.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
  22.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
  23.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],  
  24.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],  
  25.                       [NSValuevalueWithCGPoint:CGPointMake(self.center.x, self.center.y)],  
  26.                       nil];  
  27.     [animationKey setValues:array];  
  28.     [array release];  
  29.       
  30.     NSArray *times = [[NSArrayalloc] initWithObjects:  
  31.                       [NSNumbernumberWithFloat:0.1f],  
  32.                       [NSNumbernumberWithFloat:0.2f],  
  33.                       [NSNumbernumberWithFloat:0.3f],  
  34.                       [NSNumbernumberWithFloat:0.4f],  
  35.                       [NSNumbernumberWithFloat:0.5f],  
  36.                       [NSNumbernumberWithFloat:0.6f],  
  37.                       [NSNumbernumberWithFloat:0.7f],  
  38.                       [NSNumbernumberWithFloat:0.8f],  
  39.                       [NSNumbernumberWithFloat:0.9f],  
  40.                       [NSNumbernumberWithFloat:1.0f],  
  41.                       nil];  
  42.     [animationKey setKeyTimes:times];  
  43.     [times release];  
  44.       
  45.     [self.layeraddAnimation:animationKey forKey:@"TextFieldShake"];  
  46. }  
  47.   
  48. @end  
  49. //TextField的晃动:End  


41.UIButton去除按下时的状态

btn2.adjustsImageWhenHighlighted = NO; 


42.获得设备的电量

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];


if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) {

    NSLog(@"Device is charging.");

}


43.退出程序

- (void) animationFinished:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context

{

if ([animationIDcompare:@"exitApplication"] ==0)

    {

       exit(0);

    }

}


- (void) exitApplication

{

    UIWindow *window = [[UIApplicationsharedApplication] keyWindow];

    

    [UIViewbeginAnimations:@"exitApplication"context:nil];

[UIViewsetAnimationDuration:0.75];

[UIViewsetAnimationDelegate:self];

[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlDownforView:window cache:NO];

[UIViewsetAnimationDidStopSelector:@selector(animationFinished: finished: context:)];

    window.bounds =CGRectMake(512,384, 0, 0);

[UIViewcommitAnimations];

}


44.画文字

  1. //设置画笔线条粗细  
  2. CGContextSetLineWidth(context, 1.0);  
  3. //设置矩形填充颜色:红色  
  4. CGContextSetRGBFillColor (context, 1.0, 0.0, 0.0, 1.0);  
  5. //设置字体  
  6. UIFont *font = [UIFont boldSystemFontOfSize:31.0];  
  7. //在指定的矩形区域内画文字  
  8. [text drawInRect:rect withFont:font];


45.itunes图标

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


46.两个应用之间传递信息

第一步:

在目标程序(通过订制的url开打的程序)中,设置订制的url,订制方法如下:

打开plist文件添加一个键值对URL types,并设置成如下形式:



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


第二步:

在其它的应用中打开第一步中的应用,如下:(看见"JJMFAPP:"没,这个就是第一步设置的url协议)

NSURL *jjmfURL = [NSURLURLWithString:@"JJMFAPP:"];

    if ([[UIApplicationsharedApplication] canOpenURL:jjmfURL])

    {

        [[UIApplicationsharedApplication] openURL:jjmfURL];

    }


如果要传递参数则如下:(规则是 开头必须是订制的url协议如:JJMFAPP:,随后跟参数,参数之间用&隔开)

        NSString *dataToPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];

       int updataID = [usersDefaultintegerForKey:@"JJMFAPP"];

       NSString *informationString = [NSStringstringWithFormat:@"JJMFAPP:message=%@&updataID=%d",dataToPath,updataID];

        informationString = [informationStringstringByReplacingOccurrencesOfString:@" "withString:@"%20"];

       NSURL *updataURL = [NSURLURLWithString:informationString];

//        NSLog(@"%@",updataURL);

       if ([[UIApplicationsharedApplication] canOpenURL:updataURL])

        {

            [[UIApplicationsharedApplication] 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:[URLString rangeOfString:@"UPDATAJJMF:message="].location+19];

        NSMutableCharacterSet *set = [[NSMutableCharacterSetalloc] init];

        [set addCharactersInString:@"&="];

       NSArray *pathArray = [URLString componentsSeparatedByCharactersInSet:set];

        [setrelease];

        URLString = [pathArrayobjectAtIndex:1];

        Arguments2App *arg2app = [Arguments2AppsharedArguments];

        arg2app.groupid = [[pathArrayobjectAtIndex:3]intValue];

        [arg2appwriteToUserDefaults];

    

    URLString = [URLString stringByReplacingOccurrencesOfString:@"%20"withString:@" "];

   BOOL pathExists;

   BOOL yes = [[NSFileManagerdefaultManager] fileExistsAtPath:URLStringisDirectory:&pathExists];

   if (yes && pathExists)

    {

       self.viewController.upToPath = URLString;

        

       NSUserDefaults *usersDefault = [NSUserDefaultsstandardUserDefaults];

        [usersDefaultsetObject:URLString forKey:@"UPDATATOPATH"];

        [usersDefaultsynchronize];

    }

   else

    {

       self.viewController.upToPath =nil;

    }

    

    return YES;

}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions此方法中也可以得到订制的url信息

    {//处理应用程序间信息共享

        NSString *sourceApp = [launchOptionsobjectForKey:UIApplicationLaunchOptionsSourceApplicationKey];

        NSURL *url = [launchOptionsobjectForKey:UIApplicationLaunchOptionsURLKey];

       NSString *msg = [NSStringstringWithFormat:@"sourceApp:%@,url:%@",sourceApp, url];

       UIAlertView *alert = [[UIAlertViewalloc

                             initWithTitle:NSLocalizedString(@"test message",nil)

                             message:msg

                             delegate:self 

                             cancelButtonTitle:nilotherButtonTitles:@"OK",nil];

        [alertshow];     

        [alertrelease];

    }



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 = [self dateInFormat:1353635983563 format:str];

 NSLog(@"createdAt: %@",time);


49.数组排序

1.第一种方法

NSSortDescriptor *sorts;

switch (segment.selectedSegmentIndex)

{

case 0:

sorts = [[NSSortDescriptoralloc] initWithKey:@"subject" ascending: YES];

break;

case 1:

sorts = [[NSSortDescriptoralloc] initWithKey:@"priority"ascending: YES];

break;

case 2:

default:

sorts = [[NSSortDescriptoralloc] initWithKey:@"date" ascending: YES];

break;

};

NSArray *arr = [NSArrayarrayWithObject: sorts];

    [tododb.todolist.todoarraysortUsingDescriptors: arr];


2.第二种方法

//字典的keys数组,按从小到大的顺序排列

    keysArray = [[[productDicallKeys] sortedArrayUsingComparator:^(id obj1,id obj2){

       if ([obj1 integerValue] > [obj2integerValue])

        {

            return (NSComparisonResult)NSOrderedDescending;

        }

       if ([obj1 integerValue] < [obj2integerValue])

        {

            return (NSComparisonResult)NSOrderedAscending;

        }

        return (NSComparisonResult)NSOrderedSame;

    }]retain];


50.日期装换成字符串

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];

    [dateFormatter setLocale:locale];//location设置为中国

    [locale release];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss EEEE"];

    

    todayDate = [NSDate date];

    

    dateLabel.text = [dateFormatter stringFromDate:todayDate];


51.摆动动画

1.

//添加登陆界面

- (void)addLandingView

{//添加登陆界面

    matView = [[UIViewalloc] initWithFrame:CGRectMake(0, 0, 1024, 748)];

    matView.backgroundColor = [UIColorclearColor];

    [self.viewaddSubview:matView];

    [matView release];

    

    JJMFLandingView *landingView = [[JJMFLandingViewalloc] initWithFrame:CGRectMake(0, 0, 500, 240)];

    landingView.center =CGPointMake(512, 274);

    landingView.deleget =self;

    [self.viewaddSubview:landingView];

    [landingViewrelease];

    

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

    [animationKeysetDuration:1.f];

    NSArray *array = [[NSArrayalloc] 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];

    [animationKeysetValues:array];

    [arrayrelease];

    

    NSArray *times = [[NSArrayalloc] initWithObjects:

                      [NSNumbernumberWithFloat:0.1f], 

                      [NSNumbernumberWithFloat:0.25f], 

                      [NSNumbernumberWithFloat:0.4f], 

                      [NSNumbernumberWithFloat:0.6f], 

                      [NSNumbernumberWithFloat:0.8f], 

                      [NSNumbernumberWithFloat:1.0f], nil];

    [animationKeysetKeyTimes:times];

    [timesrelease];

    

    [landingView.layeraddAnimation:animationKey forKey:@"showLandView"];

}


2.

  1. /* 
  2. * pointToAngle 按角度旋转 
  3. * @angel CGFloat 角度 
  4. * @duration CGFloat 动画执行时间 
  5. */  
  6. - (void) pointToAngle:(CGFloat) angle Duration:(CGFloat) duration  
  7. {  
  8.     CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"transform"];   
  9.     NSMutableArray *values=[NSMutableArray array];   
  10.     anim.duration = duration;  
  11.     anim.autoreverses = NO;  
  12.     anim.fillMode = kCAFillModeForwards;  
  13.     anim.removedOnCompletion= NO;  
  14.       
  15.     CGFloat distance = angle/10;  
  16.     //设置转动路径,不能直接用 CABaseAnimation toValue,那样是按最短路径的,转动超过180度时无法控制方向  
  17.      int i = 1;  
  18.     for(;i<=10;i++){  
  19.         [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*i)], 0, 0, 1)]];  
  20.         }  
  21.     //添加缓动效果  
  22.      [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i))], 0, 0, 1)]];  
  23.      [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-2))], 0, 0, 1)]];       
  24.      [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-1))], 0, 0, 1)]];  
  25.                                                                              
  26.     anim.values=values; ;  
  27.     [pointer.layer addAnimation:anim forKey:@"cubeIn"];  
  28.       
  29.     gaugeAngle = gaugeAngle+angle;  
  30.       
  31. }  
0 0
原创粉丝点击