iphone开发常用代码2

- (NSString *)URLEncodedString:(NSString *)string{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                       (CFStringRef)string,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8);
    [result autorelease];
    return result;
}

//生成nonce
- (NSString *)generateNonce{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    NSMakeCollectable(theUUID);
    return [(NSString *)string stringByReplacingOccurrencesOfString:@"-" withString:@""];


    //return (NSString *)string;
}

//生成Timestamp
- (NSString *)generateTimestamp{
    return [[NSString stringWithFormat:@"%d", time(NULL)] retain];
}

iPhone键盘改变颜色
只有这2种数字键盘才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad
keyboardAppearance = UIKeyboardAppearanceAlert
代码如下:
 
  1.    NSArray *ws = [[UIApplication sharedApplication] windows];
  2.     for(UIView *w in ws){
  3.         NSArray *vs = [w subviews];
  4.         for(UIView *v in vs){
  5.             if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"]){
  6.                 v.backgroundColor = [UIColor redColor];
  7.             }
  8.         }
  9.     }

从一个界面push到下一界面左上角返回按钮文字设置

在父viewController中如下设置:
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];


    backbutton.title = @"返回列表";
    self.navigationItem.backBarButtonItem = backbutton;
    [backbutton release];

navigationbar的back键触发其他事件
UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)];
[back addTarget:self act
ion:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];
[back setImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = loginButtonItem
[back release];
[backButtonItem release];
防止屏幕暗掉锁屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

将图片从左到右翻页效果显示

   
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];
    [imageView setImage:[UIImage imageNamed:@"Bg.jpg"]];
    self.myImageView =imageView;
    [self.view addSubview:imageView];
    [imageView release];
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    [myImageView setFrame:CGRectMake(0, 0, 310, 470)];   
    [UIView commitAnimations];

让覆盖在下面层的视图接受触摸事件

searchImage.exclusiveTouch = YES;//第一层
searchImage.userInteractionEnabled = NO;
myMapView.exclusiveTouch = NO;//第二层
myMapView.userInteractionEnabled = YES;


View的缩放


NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain];
[UIView beginAnimations:nil context:touchPointValue];
transform = CGAffineTransformMakeScale(0.1,0.21);
firstPieceView.transform = transform;
[UIView commitAnimations];   

代码循环添加按钮,其他空间也可以用类似方法添加


- (void)viewDidLoad {
    [super viewDidLoad];
    for(int i = 0; i < 5; i++){
        CGRect frame;
        Btn[i] = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
        [Btn[i] setImage:[UIImage imageNamed:@"Button.png"] forState:UIControlStateNormal];//设置按钮图片
        frame.size.width = 55;//设置按钮坐标及大小
        frame.size.height = 84;
        frame.origin.x = (i%5)*57+5;
        frame.origin.y = 10;
        [Btn[i] setFrame:frame];
        [Btn[i] setBackgroundColor:[UIColor clearColor]]; 内容来自泠云天天在线
        [Btn[i] addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:Btn[i]];
        [Btn[i] release];
    }
}
//响应按钮事件
-(void)btnPressed:(id)sender{
    for(int i = 0; i < 5;i++){
        if([sender isEqual:Btn[i]]){
            NSLog(@"Btn[%d]:",i);
        }
    }
}

去除nsstring中的空格,table 以及newline,nextline

NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *username = [mUsernameField stringValue];
username = [username stringByTrimmingCharactersInSet:whitespace];

UIImagePickerController


UIImagePickerController选择、显示图片或视频,主要注意UIImagePickerController几个属性的设置
一:UI 显示样式,显示的格式确定
1:sourceType
@property(nonatomic) UIImagePickerControllerSourceType sourceType
enum {
UIImagePickerControllerSourceTypePhotoLibrary, 本文来自泠云天天在线
UIImagePickerControllerSourceTypeCamera,
UIImagePickerControllerSourceTypeSavedPhotosAlbum
};
typedef NSUInteger UIImagePickerControllerSourceType;
sourceType用来确定用户界面显示的样式:
共三种格式(模拟器上的效果图)
UIImagePickerControllerSourceTypePhotoLibrary,
UIImagePickerControllerSourceTypeCamera,
iphone开发常用代码(不断更新) - 勇者之尊 - 等待

UIImagePickerControllerSourceTypeSavedPhotosAlbum
iphone开发常用代码(不断更新) - 勇者之尊 - 等待
为了区分是否支持视频格式,一般要用到下面这个函数,以便确定mediaTypes。
+ (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType
2:   mediaTypes
@property(nonatomic,copy) NSArray *mediaTypes
mediaTypes用来确定再picker里显示那些类型的多媒体文件,图片?视频?
+ (NSArray *)availableMediaTypesForSourceType:(UIImagePickerControllerSourceType)sourceType
二:选取动作处理
UIImagePickerControllerDelegate
通过代理来完成用户在选中图片,或者choose视频时的处理方式:

共有三个可选的代理方法
– imagePickerController:didFinishPickingMediaWithInfo: 
– imagePickerControllerDidCancel: 
– imagePickerController:didFinishPickingImage:editingInfo:   Deprecated in iPhone OS 3.0

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
info中包括选取的照片,视频的主要信息
NSString *const UIImagePickerControllerMediaType;         选取的类型 public.image  public.movie
NSString *const UIImagePickerControllerOriginalImage;    修改前的UIImage object.
NSString *const UIImagePickerControllerEditedImage;      修改后的UIImage object.
NSString *const UIImagePickerControllerCropRect; 原始图片的尺寸NSValue object containing a CGRect data type
NSString *const UIImagePickerControllerMediaURL;          视频在文件系统中 的 NSURL地址
保存视频主要时通过获取其NSURL 然后转换成NSData
实例代码如下:

- (void) pickImage: (id) sender

{ 本文来自泠云天天在线

UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; copyright lyttzx.com

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
lyttzx.com

     ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;

      ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];  

        } 

ipc.delegate = self;

ipc.allowsImageEditing = NO;

[self presentModalViewController:ipc animated:YES];

}

 

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ 内容来自泠云天天在线

NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; 泠云工作室

if ([mediaType isEqualToString:@"public.image"]){

// UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSLog(@"found an image");

[UIImageJPEGRepresentation(image, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];

    SETIMAGE(image); lyttzx.com

CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);

}

else if ([mediaType isEqualToString:@"public.movie"]){

 

NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

NSLog(@"found a video"); copyright lyttzx.com

        NSData *webData = [NSData dataWithContentsOfURL:videoURL];

//NSData *video = [[NSString alloc] initWithContentsOfURL:videoURL];

[webData writeToFile:[self findUniqueMoviePath] atomically:YES];

CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]); 本文来自泠云天天在线

// NSLog(videoURL);

}

[picker dismissModalViewControllerAnimated:YES];

} 内容来自泠云天天在线


UITextInputTraits属性


 autocapitalizationType            设置键盘自动大小写的属性     UITextAutocapitalizationTypeNone
autocorrectionType  property  设置是否有自动修改提示   UITextAutocorrectionTypeNo
enablesReturnKeyAutomatically   Boolean值-设置在用户没有输入是returnKey禁用,默认值NO
keyboardAppearance  设置键盘显示方式  除了默认模式  还有一个UIKeyboardAppearanceAlert模式
keyboardType               设置键盘类型   UIKeyboardTypePhonePad 等
returnKeyType              设置renturnKey按键上的提示文字     UIReturnKeyGo   UIReturnKeyNext


secureTextEntry          
BOOL值  -- 设置是否是密码保护模式输入

如下:
设置登录用的 输入框 UITextField
用户名输入框:
m_TF_username = [[UITextField alloc] initWithFrame:my_frame];
m_TF_username.borderStyle = UITextBorderStyleNone;
m_TF_username.clearButtonMode = UITextFieldViewModeWhileEditing;
m_TF_username.delegate = self;
m_TF_username.returnKeyType = UIReturnKeyNext;
m_TF_username.autocapitalizationType = UITextAutocapitalizationTypeNone;
[m_TF_username becomeFirstResponder];
密码输入框:
m_TF_password = [[UITextField alloc] initWithFrame:my_frame];
m_TF_password.borderStyle = UITextBorderStyleNone;
m_TF_password.clearButtonMode = UITextFieldViewModeWhileEditing;
m_TF_password.delegate = self;
m_TF_password.returnKeyType = UIReturnKeyGo;
m_TF_password.secureTextEntry =YES;

键盘透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

状态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。

截取屏幕图片
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));

//renderInContext 呈现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
  
 //返回一个基于当前图形上下文的图片
 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
 
 //移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();

//以png格式返回指定图片的数据
imageData = UIImagePNGRepresentation(aImage);


更改cell选中的背景
    UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
    cell.selectedBackgroundView = myview;

在数字键盘上添加button:
//定义一个消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注册一个观察员 name:消息名称
- (void)keyboardWillShow:(NSNotification *)note {
    // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    [doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
   
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回应用程序window
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) //遍历window上的所有subview
    {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if([[keyboard de(责任编辑:泠云)

你可能感兴趣的:(iPhone开发)