iphone可以用得到的一些代码

iphone可以用得到的一些代码

精选 转载

命苦 博主文章分类:iPhone 开发

文章标签 职场 移动开发 休闲 iphone 代码 文章分类 Hive 大数据

iphone可以用得到的一些代码_iphone 代码 2011年7月5日
转自:http://fei263.blog.163.com/blog/static/927937242009526112420548/
- (NSString *)URLEncodedString:(NSString *)string{
    NSString *result = (NSStrin*)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
代码如下:
NSArray *ws = [[UIApplication sharedApplication] windows];
    for(UIView *w in ws){
        NSArray *vs = [w subviews];
        for(UIView *v in vs){
           if([[NSStringstringWithUTF8String:object_getClassName(v)]isEqualToString:@"UIKeyboard"]){
                v.backgroundColor = [UIColor redColor];
            }
        }
    }

从一个界面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 p_w_picpathNamed:@"返回按钮.png"] forState:UIControlStateNormal];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = loginButtonItem
[back release];
[backButtonItem release];

防止屏幕暗掉锁屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

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

   
 
UIImageView *p_w_picpathView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];
  [p_w_picpathView setImage:[UIImage p_w_picpathNamed:@"Bg.jpg"]];
  self.myImageView =p_w_picpathView;
  [self.view addSubview:p_w_picpathView];
  [p_w_picpathView 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 p_w_picpathNamed:@"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可以用得到的一些代码_职场_02

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

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

- (void)p_w_picpathPickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
info中包括选取的照片,视频的主要信息
NSString *const UIImagePickerControllerMediaType;         选取的类型 public.p_w_picpath  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];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
     ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
      ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];  
        } 
ipc.delegate = self;
ipc.allowsImageEditing = NO;
[self presentModalViewController:ipc animated:YES];
}
 
- (void)p_w_picpathPickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.p_w_picpath"]){
// UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *p_w_picpath = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSLog(@"found an p_w_picpath");
[UIImageJPEGRepresentation(p_w_picpath, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];
    SETIMAGE(p_w_picpath);
CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@"/Documents"]]);
}
else if ([mediaType isEqualToString:@"public.movie"]){
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"found a video");
        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格式返回指定图片的数据
p_w_picpathData = UIImagePNGRepresentation(aImage);


更改cell选中的背景
    UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage p_w_picpathNamed:@"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 p_w_picpathNamed:@"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 description] hasPrefix:@"<UIKeyboard"] == YES)
        [keyboard addSubview:doneButton];
    }
}

正则表达式使用:
被用于正则表达式的字串必须是可变长的,不然会出问题

将一个空间放在视图之上
[scrollView insertSubview:searchButton aboveSubview:scrollView];

从本地加载图片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src='http://fei263.blog.163.com/blog/0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];

从网页加载图片并让图片在规定长宽中缩小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='http://fei263.blog.163.com/blog/%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];
将网页加载到webview上通过javascript获取里面的数据,如果只是发送了一个连接请求获取到源码以后可以用正则表达式进行获取数据
NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";
NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];

用NSString怎么把UTF8转换成unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];

View自己调用自己的方法:
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//×××段为方法名,和延迟几秒执行.

显示图像:
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage p_w_picpathNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];

WebView:
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];

显示网络活动状态指示符
这是在iPhone左上部的状态栏显示的转动的图标指示有背景发生网络的活动。
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;

动画:一个接一个地显示一系列的图象
NSArray *myImages = [NSArray arrayWithObjects: [UIImage p_w_picpathNamed:@"myImage1.png"], [UIImage p_w_picpathNamed:@"myImage2.png"], [UIImage p_w_picpathNamed:@"myImage3.png"], [UIImage p_w_picpathNamed:@"myImage4.gif"], nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages; //animationImages属性返回一个存放动画图片的数组
myAnimatedView.animationDuration = 0.25; //浏览整个图片一次所用的时间
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 动画重复次数
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];

动画:显示了something在屏幕上移动。注:这种类型的动画是“开始后不处理” -你不能获取任何有关物体在动画中的信息(如当前的位置) 。如果您需要此信息,您会手动使用定时器去调整动画的X和Y坐标
这个需要导入QuartzCore.framework
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];

Draggable items//拖动项目
Here's how to create a simple draggable p_w_picpath.//这是如何生成一个简单的拖动图象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point 检索接触点
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Move relative to the original touch point 相对以前的触摸点进行移动
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
3. Now instantiate the new class as you would any other new p_w_picpath and add it to your view
//实例这个新的类,放到你需要新的图片放到你的视图上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage p_w_picpathNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];

线程:
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
{
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
}
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];

Alerts
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];

Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews])
{
if (anImage.tag == 1)
        { // do something }
}
posted @ 2011-07-05 10:59 黑暗天使 阅读(10) | 评论(0) | 编辑
iphone可以用得到的一些代码_iphone 代码 2011年6月16日
先引用一段: http://www.cnblogs.com/haipingwu/
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

这个函数是UIImage的一个实例函数,它的功能是创建一个内容可拉伸,而边角不拉伸的图片,需要两个参数,第一个是不拉伸区域和左边框的宽度,第二个参数是不拉伸区域和上边框的宽度。

第一次用这个函数的时候一直搞不懂为什么只要两个参数就行,至少应该指定左上角和右下角,总共四个参数啊。后来读读文档才明白,只需要两个参数就行了。

参数的意义是,如果参数指定10,5。那么,图片左边10个像素,上边5个像素。不会被拉伸,x坐标为11和一个像素会被横向复制,y坐标为6的一个像素会被纵向复制。注意:只是对一个像素进行复制到一定宽度。
附:两个聊天用的汽泡,与参数值。
iphone可以用得到的一些代码_休闲_0521,13。
iphone可以用得到的一些代码_休闲_0615,13。
再看看实例,代码如下:
UIImage* p_w_picpath =[UIImage p_w_picpathNamed:@"p_w_picpath.png"];
UIImageView* p_w_picpathView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
[p_w_picpathView setImage:[p_w_picpath stretchableImageWithLeftCapWidth:40 topCapHeight:40]];
[self.view addSubview:p_w_picpathView];
[p_w_picpathView release]; <br>
最后看看结果,不解释:
原图:
iphone可以用得到的一些代码_职场_07
结果图:
iphone可以用得到的一些代码_休闲_08
结束,不解释
<br>
posted @ 2011-06-16 17:45 黑暗天使 阅读(21) | 评论(0) | 编辑
 
在实际的应用中,总感觉圆角的东西比较好看, 像button,label,p_w_picpath等等,以前的时候我就经常给那些控件添加一个UIImageView作为背景,再搞张圆角的图片,不过今天发现了新方法看代码
viewT.layer.cornerRadius = 10;//设置那个圆角的有多圆
viewT.layer.borderWidth = 10;//设置边框的宽度,当然可以不要
viewT.layer.borderColor = [[UIColor redColor] CGColor];//设置边框的颜色
viewT.layer.masksToBounds = YES;//设为NO去试试
其实的viewT是UIView的实例,当然也可以是他的子类实例哈。
最后别忘记添加QuartzCore.framework这个库,还有在你的文件中包含#import <QuartzCore/QuartzCore.h>这句哦
posted @ 2011-06-16 16:22 黑暗天使 阅读(7) | 评论(0) | 编辑
iphone可以用得到的一些代码_iphone 代码 2011年5月9日
一、获取系统所支持的国际化信息 在国际化之前,你可以在iphone中的”设置->通用->多语言环境->语言”中来查看你的iphone支持哪些语言,
  当然也可以写一段代码测试一下你的iphone都支持 哪些语言.测试代码如下:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray
*languages = [defaults objectForKey:@"AppleLanguages"]; NSLog(@"%@", languages);
 注:NSUserDefaults类用来取得用户人默认信息.
二、在Xcode中建立多语言文档
  1.在Resources分类下新建文档(右鍵/Add/New File…)
  2.在模板对话框中选择Other,然后再选择Strings File
  3.将文件保存名设置为Localizable.strings
  4.在Localizable.strings 文件上按右键并选择 Get Info
  5.点击信息界面的Make File Localizable,然后再将Tab标签切换到General
  6.输入新的语言名称 zh 後按 Add,些时有English与zh两种语言,你还可以增加其它语言.
三、在源代码中使用NSLocalizedString来引用国际化文件
  //括号里第一个参数是要显示的内容,与各Localizable.strings中的id对应
  //第二个是对第一个参数的注释,一般可以为空串
[_alertView setTitle:NSLocalizedString(@"Submitted successfully",@"")];
四、使用Terminal的genstrings命令进行生成资源文件 打开Terminal,
  然后cd到工程所在的目录,然后使用genstrings来生成自动从源代码中生成资源文件.
  例如,项目的目录为:/user/project/test01,
  则命令如下: genstrings -o English.lproj ./classes/*.m genstrings -o zh.lproj ./classes/*.m
五、编辑各Localizable.strings文件
  从第四步中得到了与代码对应的资源文件,最后我们需要对这些资源文件翻译成对应的语言就可以了.
  如在Localizable.strings(zh)中,把等号后的字进行编译成中文.
"Submitted successfully" = "提交成功"
  重新编译整个工程后,就会在不同的语言环境下得到相应的语言显示.
posted @ 2011-05-09 17:51 黑暗天使 阅读(105) | 评论(0) | 编辑
iphone可以用得到的一些代码_iphone 代码 2011年5月5日
对kvo/kvc做了简单的介绍,可作为入门读物。
有些术语描述不够精确请指正。
欢迎讨论。
Kvo是Cocoa的一个重要机制,他提供了观察某一属性变化的方法,极大的简化了代码。这种观察-被观察模型适用于这样的情况,比方说根据A(数 据类)的某个属性值变化,B(view类)中的某个属性做出相应变化。对于推崇MVC的cocoa而言,kvo应用的地方非常广泛。(这样的机制听起来类 似Notification,但是notification是需要一个发送notification的对象,一般是 notificationCenter,来通知观察者。而kvo是直接通知到观察对象。)
适用kvo时,通常遵循如下流程:
1 注册:
-(void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
keyPath就是要观察的属性值,options给你观察键值变化的选择,而context方便传输你需要的数据(注意这是一个void型)
2 实现变化方法:
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary
*)change context:(void *)context
change里存储了一些变化的数据,比如变化前的数据,变化后的数据;如果注册时context不为空,这里context就能接收到。
是不是很简单?kvo的逻辑非常清晰,实现步骤简单。
说了这么多,大家都要跃跃欲试了吧。可是,在此之前,我们还需要了解KVC机制。其实,知道了kvo的逻辑只是帮助你理解而已,要真正掌握的,不在 于kvo的实现步骤是什么,而在于KVC,因为只有符合KVC标准的对象才能使用kvo(强烈推荐要使用kvo的人先理解KVC)。
KVC是一种间接访问对象属性(用字符串表征)的机制,而不是直接调用对象的accessor方法或是直接访问成员对象。
key就是确定对象某个值的字符串,它通常和accessor方法或是变量同名,并且必须以小写字母开头。Key path就是以“.”分隔的key,因为属性值也能包含属性。比如我们可以person这样的key,也可以有key.gender这样的key path。
获取属性值时可以通过valueForKey:的方法,设置属性值用setValue:forKey:。与此同时,KVC还对未定义的属性值定义了 valueForUndefinedKey:,你可以重载以获取你要的实现(补充下,KVC定义载NSKeyValueCoding的非正式协议里)。
在O-C 2.0引入了property,我们也可以通过.运算符来访问属性。下面直接看个例子:
@property NSInteger number;

instance.number
= 3;
[instance setValue:[NSNumber numberWithInteger:
3] forKey:@"number"];
注意KVC中的value都必须是对象。
以上介绍了通过KVC来获取/设置属性,接下来要说明下实现KVC的访问器方法(accessor method)。Apple给出的惯例通常是:
-key:,以及setKey:(使用的name convention和setter/getter命名一致)。对于未定义的属性可以用setNilValueForKey:。
至此,KVC的基本概念你应该已经掌握了。之所以是基本,因为只涉及到了单值情况,kvc还可以运用到对多关系,这里就不说了,留给各位自我学习的空间
接下来,我们要以集合为例,来对掌握的KVC进行一下实践。
之所以选择array,因为在ios中,array往往做为tableview的数据源,有这样的一种情况:
 假设我们已经有N条数据,在进行了某个操作后,有在原先的数据后多了2条记录;或者对N中的某些数据进行更新替换。不使用KVC我们可以使用 reloadData方法或reloadRowsAtIndexPaths。前一种的弊端在于如果N很大消耗就很大。试想你只添加了几条数据却要重载之前 N数据。后一种方法的不足在于代码会很冗余,你要一次计算各个indexPath再去reload,而且还要提前想好究竟在哪些情况下会引起数据更新,
倘若使用了KVC/kvo,这样的麻烦就迎刃而解了,你将不用关心追加或是更新多少条数据。
下面将以添加数据为例,说明需要实现的方法:
实现insertObject:inKeyAtIndex:或者insertKey:atIndexes。同时在kvo中我们可以通过change这个dictionary得知发生了哪种变化,从而进行相应的处理。
另附关于KVC/KVO的资料:点击下载
posted @ 2011-05-05 15:14 黑暗天使 阅读(115) | 评论(0) | 编辑
 
- (NSString *)intervalSinceNow: (NSString *) theDate
{

NSDateFormatter
*date=[[NSDateFormatter alloc] init];
[date setDateFormat:
@"yyyy-MM-dd HH:mm:ss"];
NSDate
*d=[date dateFromString:theDate];

NSTimeInterval late
=[d timeIntervalSince1970]*1;


NSDate
* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval now
=[dat timeIntervalSince1970]*1;
NSString
*timeString=@"";

NSTimeInterval cha
=now-late;

if (cha/3600<1) {
timeString
= [NSString stringWithFormat:@"%f", cha/60];
timeString
= [timeString substringToIndex:timeString.length-7];
timeString
=[NSString stringWithFormat:@"%@分钟前", timeString];

}
if (cha/3600>1&&cha/86400<1) {
timeString
= [NSString stringWithFormat:@"%f", cha/3600];
timeString
= [timeString substringToIndex:timeString.length-7];
timeString
=[NSString stringWithFormat:@"%@小时前", timeString];
}
if (cha/86400>1)
{
timeString
= [NSString stringWithFormat:@"%f", cha/86400];
timeString
= [timeString substringToIndex:timeString.length-7];
timeString
=[NSString stringWithFormat:@"%@天前", timeString];

}
[date release];
return timeString;
}

posted @ 2011-05-05 15:10 黑暗天使 阅读(46) | 评论(0) | 编辑
 
在做地图有关的程序时,我们经常需要用户在地图上指定位置我们再用大头针标记。
1、在viewDidLoad中添加我们要捕获的手势:
UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
lpress.minimumPressDuration
= 0.5;//按0.5秒响应longPress方法
lpress.allowableMovement = 10.0;
[m_mapView addGestureRecognizer:lpress];
//m_mapView是MKMapView的实例
[lpress release];
2、实现要响应的longPress方法:
- (void)longPress:(UIGestureRecognizer*)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
return;
}


//坐标转换
CGPoint touchPoint = [gestureRecognizer locationInView:m_mapView];
CLLocationCoordinate2D touchMapCoordinate
=
[m_mapView convertPoint:touchPoint toCoordinateFromView:m_mapView];



MKPointAnnotation
* pointAnnotation = nil;
pointAnnotation
= [[MKPointAnnotation alloc] init];
pointAnnotation.coordinate
= touchMapCoordinate;
pointAnnotation.title
= @"名字";

[m_mapView addAnnotation:m_pointAnnotation];

[pointAnnotation release];

}
3,响应MKMapView的代理方法:
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{

if ([annotation isKindOfClass:[MKUserLocation class]])
{
[self.navigationItem.rightBarButtonItem setEnabled:YES];
//导航栏右边回到当前位置的按钮可用
return nil;
}



static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
MKPinAnnotationView
* customPinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];

if (!customPinView) {
customPinView
= [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];

customPinView.pinColor
= MKPinAnnotationColorRe;//设置大头针的颜色
customPinView.animatesDrop = YES;
customPinView.canShowCallout
= YES;
customPinView.draggable
= YES;//可以拖动

//添加tips上的按钮
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView
= rightButton;
}
else{
customPinView.annotation
= annotation;
}
return customPinView;

}
4、实现showDetails方法:
- (void)showDetails:(UIButton*)sender
{

}
关于MKMapView的更多请参加apple的MapCallouts例子
posted @ 2011-05-05 10:52 黑暗天使 阅读(198) | 评论(0) | 编辑
 
 
-(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 p_w_picpathWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);

return grayImage;
}

其中,CGColorSpaceCreateDeviceGray会创建一个设备相关的灰度颜色空间的引用。
posted @ 2011-05-05 10:04 黑暗天使 阅读(56) | 评论(0) | 编辑
iphone可以用得到的一些代码_iphone 代码 2011年4月21日
  个人觉得用这个东西在不同的viewcontroller间传东西很方便的
发消息
  [[NSNotificationCenter defaultCenter] postNotificationName:@"popView"/*消息名字,在添加监听时会用到*/       object:@"ShowHomeLineViewController"/*传的参数,多个参数就可以用数组啦*/];
收消息
1、添加监听:
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Show:)/*收到消息后的响应函数*/ name:@"popView"/*消息名字,在发消息时  指定的*/ object:nil];
2、消息处理(实现前面的Show:函数)
-(void)Show:(NSNotification*)notification
{
    NSString* str = (NSString*)[notification object];//这里取出刚刚从过来的字符串
}
3、不要忘记移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"popView" object:nil];
  • 收藏
  • 评论
  • 举报

上一篇:飞机游戏策划

下一篇:程序员的情书

提问和评论都可以,用心的回复会被更多人看到 评论
发布评论
相关文章

举报文章

请选择举报类型

内容侵权 涉嫌营销 内容抄袭 违法信息 其他

具体原因

包含不真实信息 涉及个人隐私

补充说明

0/200

上传截图

格式支持JPEG/PNG/JPG,图片不超过1.9M

已经收到您得举报信息,我们会尽快审核