iPhone开发中的技巧整理

1、NSCalendar用法

-(NSString *) getWeek:(NSDate *)d
{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekCalendarUnit;
NSDateComponents *components = [calendar components:units
fromDate:d];
[calendar release];
switch ([components weekday]) {
case1:
return @"Monday"; break;
case2:
return @"Tuesday"; break;
case3:
return @"Wednesday"; break;
case4:
return @"Thursday"; break;
case5:
return @"Friday"; break;
case6:
return @"Saturday"; break;
case7:
return @"Sunday"; break;
default:
return @"NO Week"; break;
}
NSLog(@"%@",components); 
}
 
2、将网络数据读取为字符串
-(NSString *)getDataByURL:(NSString *)url {
return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}
 
3、读取⺴络图⽚
-(UIImage *)getImageByURL:(NSString *)url {
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}
 
4、多线程(这种方式,只管建立线程,不管回收线程)
[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];
-(void)scheduleTask
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; 
}
 
如果有参数,则这么⽤
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];
-(void)scheduleTask:(NSDate *)mdate
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; }
 
在线程⾥运⾏主线程⾥的⽅法
[self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
 
5、⽤户缺省值NSUserDefaults读取:
NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
NSArray *languages = [df objectForKey:@"AppleLanguages"]; 
NSLog(@"all language is %@",languages);
NSLog(@"index is %@",[languages objectAtIndex:0]);
NSLocale *currentLocale = [NSLocale currentLocale];
NSLog(@"language Code is %@",[currentLocale objectForKey:NSLocaleLanguageCode]); 
NSLog(@"Country Code is %@",[currentLocale objectForKey:NSLocaleCountryCode]);
 
6、view之间转换的动态效果设置
SecondViewController *secondViewController = [[SecondViewController alloc] init];
secondViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//⽔水平翻转
[self.navigationController presentModalViewController:secondViewController animated:YES];
[secondViewController release];
 
 
7、UIScrollView 滑动用法: -(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(@"正在滑动中。。")
}
//⽤户直接滑动UIScrollView,可以看到滑动条
-(void)scrollViewDidEndDelerating:(UIScrollView *)scrollView {
}
//通过其他控件触发UIScrollView滑动,看不到滑动条
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
}
//UIScrollView 设置滑动不超出本⾝身范围
[scrollView setBounces:NO]; 
 
8、iphone的系统目录:
//得到Document:目录
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到temp临时目录
NSString *temPath = NSTemporaryDirectory();
//得到目录上的文件地址
NSString *address = [paths stringByAppendingPathComponent:@"1.rtf"];
 
9、状态栏显⽰示indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
 
10、app Icon显示数字:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
 
 [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];
}
11、sqlite保存地址:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *filePath = [thePath stringByAppendingPathComponent:@"kilometer.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePathstringByAppendingPathComponent:@"kilometer2.sqlite"];
 
12、键盘弹出隐藏,textfield变位置
_tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100,
150, 260, 30)];
_tspasswordTF.backgroundColor = [UIColor redColor];
_tspasswordTF.tag = 2;
/*
Use this method to release shared resources, save user data,
_tspasswordTF.delegate = self;
[self.window addSubview: _tspasswordTF];
 
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[self animateTextField: textField up: YES]; 
}
 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self animateTextField: textField up: NO]; 
[textField resignFirstResponder];
return YES;
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up {
const int movementDistance = 80; 
// tweak as needed 
const float movementDuration = 0.3f; 
// tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil]; [UIView setAnimationBeginsFromCurrentState: YES]; [UIView setAnimationDuration: movementDuration];
self.window.frame = CGRectOffset(self.window.frame, 0, movement);
[UIView commitAnimations]; 
}
 
13、获取图片的尺⼨
CGImageRef img = [imageView.image CGImage]; 
NSLog(@"%d",CGImageGetWidth(img)); 
NSLog(@"%d",CGImageGetHeight(img));
 
14、AlertView,ActionSheet的cancelButton点击事件:
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex; // before animation and hiding view
{
  NSLog(@"cancel alertView... buttonindex = %d",buttonIndex); //当⽤用户按下Cancel按钮
  if (buttonIndex == [alertView cancelButtonIndex]){
  exit(0); 
  }
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"%s %d button = %d cancel actionSheet.....",__FUNCTION__,__LINE__, buttonIndex);
//当⽤用户按下Cancel按钮
  if (buttonIndex == [actionSheet cancelButtonIndex]) {
  exit(0);
  } 
}
15、给window设置全局背景图片
self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@""]];
 
16、tabcontroller随意切换tabbar
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController 
或者
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
或者
_tabBarController.selectedIndex = tabIndex;
 
17、计算字符串⻓度:
CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size: 18]].width;
 
18、计算点到线段的最短距离
根据结果坐标使⽤用CLLocation类的函数计算实际距离。 double
x1, y1, x2, y2, x3, y3;
double px =x2 -x1;
double py = y2 -y1;
double som = px *px + py *py;
double u =((x3 - x1)*px +(y3 - y1)*py)/som; if(u > 1)
{ u=1; }
if (u < 0) { u =0;
}
//the closest point
double x = x1 + u *px; double y = y1 + u * py; double dx = x - x3; double dy = y - y3;
double dist = sqrt(dx*dx + dy*dy);
 
19、UISearchBar背景透明 
在使用UISearchBar时,将背景⾊设定为clearColor,或者将translucent设为YES,都
不能使背景透明,经过一番研究,发现了一种超级简单和实用的⽅法:
[[searchbar.subviews objectAtIndex:0] removeFromSuperview];
背景完全消除了,只剩下搜索框本身了。
 
20、图像与缓存 :
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"icon.png"]]; // 会缓存图片
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不会缓存图⽚片
 
21、iphone对视图层的操作
// 将textView的边框设置为圆角
_textView.layer.cornerRadius = 8;
_textView.layer.masksToBounds = YES;
//给textView添加一个有色边框
_textView.layer.borderWidth = 5;
_textView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09
blue:0.07 alpha:1] CGColor]; 
//textView添加背景图片
_textView.layer.contents = (id)[UIImage imageNamed:@"31"].CGImage;
 
22、关闭当前应用
[[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
 
23、给iPhone程序添加欢迎界面
1、将你需要的欢迎界面的图片,存成Default.png 
[NSThread sleepForTimeInterval:10.0]; 这样欢迎页面就停留10秒后消失了。
 
24、NSString NSDate转换
NSString* myString= @"testing";
NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncodi ng]];
NSString* aStr =
[[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];
 
25、UIWebView中的dataDetectorTypes 
如果你希望在浏览页面时,页面上的电话号码显示成链接形式,点击电话号码就拨打电话,这时你就需要用到dataDetectorTypes了。
 
NSURL *url = [NSURL URLWithString:@"http://2015.iteye.com"]; 
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber; 
[webView loadRequest:requestObj];
 
26、打开苹果电脑浏览器的代码
如您想在 Mac 软件中集成一键打开浏览器功能,可以使用以下代码
 
[[NSWorkspace sharedWorkspace] openURLs: urls withAppBundleIdentifier:@"com.apple.Safari"
options: NSWorkspaceLaunchDefault additionalEventParamDescriptor: NULL launchIdentifiers: NULL];
 
27、设置StatusBar以及NavigationBar的样式
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque; self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
 
28、隐藏Status Bar 你可能知道一个简易的方法,那就是在程序的viewDidLoad中加入以下代码:
 
[UIApplication sharedApplication].statusBarHidden = YES; 
此法可以隐藏状态条,但问题在于,状态条所占空间依然无法为程序所用。
本篇介绍的方法依然简单,但更为奏效。通过简单的3个步骤,在plist中加入一 个键值来实现。
1. 点击程序的Info.plist
2. 右键点击任意一处,选择Add Row
3. 加入的新键值,命名为UIStatusBarHidden或者Status bar is initially hidden,然后选上这一项。
 
29、产生随机数的最佳方案
arc4random()会返回一个整型数,因此,返回1至100的随机数可以这样写: 
arc4random()%100 + 1;
 
30、string 和char转换 
NSString *cocoaString = [[NSString alloc] initWithString:@"MyString"];
const char *myCstring = [cocoaString cString];
const char *cString = "Hello";
NSString *cocoString = [[NSString alloc] initWithCString:cString];
 
31、用UIWebView在当前程序中打开网页 如果URL中带中文的话,必须将URL中的中文转成URL形式的才行。
NSString *query = [NSString stringWithFormat:@"http://www.baidu.com?q=苹 果"];
NSString *strUrl = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; 
[webView loadRequest:requestObj];
 
32、阻止ios设备锁屏 
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
或 
[UIApplication sharedApplication].idleTimerDisabled = YES; 
 
33、一条命令卸载Xcode和 iPhone SDK
sudo /Developer/Library/uninstall-devtools --mode=all
 
34、获取按钮的title
-(void)btnPressed:(id)sender {
NSString *title = [sender titleForState:UIControlStateNormal]; 
NSString *newText = [[NSString alloc] initWithFormat:@"%@",title]; 
label.text = newText;
[newText release]; 
}
 
35、NSDate to NSString
NSString *dateStr = [[NSString alloc] initWithFormat:@"%@", date];
或者
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate); 
[dateFormatter release];
 
36、图片由小到大缓慢显示的效果
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
[imageView setImage:[UIImage imageNamed:@"4.jpg"]]; 
self.ANImageView = imageView;
[self.view addSubview:imageView];
[imageView release];
CGContextRef context = UIGraphicsGetCurrentContext(); 
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
[UIView setAnimationDuration:2.5];
CGImageRef img = [self.ANImageView.image CGImage];
[ANImageView setFrame:CGRectMake(0, 0, CGImageGetWidth(img), CGImageGetHeight(img))];
[UIView commitAnimations]; 
NSLog(@"%lu",CGImageGetWidth(img));
NSLog(@"%lu",CGImageGetHeight(img));
 
37、数字转字符串
NSString *newText = [[NSString alloc] initWithFormat:@"%d",number]; 
numberlabel.text = newText;
[newText release];
 
38、随机函数arc4random() 的使用.
在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的 最大值则是 0x100000000 (4294967296),从而有更好的精度。使用 arc4random()还不需要生成随机种子,因为第一次调用的时候就会自动生成。
如:
arc4random() 来获取0到100之间浮点数
#define ARC4RANDOM_MAX 0x100000000
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
1. self.view.backgroundColor = [UIColor colorWithHue: arc4random() % 2 55 / 255
2. 3. 4.
saturation: arc4random() % 2 brightness: arc4random() % 2
alpha: 1.0];
 
39、改变键盘颜色的实现
iPhone和iPod touch的键盘颜色其实是可以通过代码更改的,这样能更匹配 App的界面风格,下面是改变iPhone键盘颜⾊色的代码。
-(void)textFieldDidBeginEditing:(UITextField *)textField {
NSArray *ws = [[UIApplication sharedApplication] windows]; 
for(UIView *w in ws)
{
NSArray *vs = [w subviews]; 
for(UIView *v in vs)
{
 
if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIPeripheralHostView"])
{
v.backgroundColor = [UIColor blueColor];
} }
} }
55 / 255 55 / 255
_textField.keyboardAppearance = UIKeyboardAppearanceAlert;//有这个设置属性 才起作用
 
40、iPhone上实现Default.png动画 添加一张和Default.png⼀一样的图片,对这个图片进行动画,从而实现Default动画的渐变消 失的效果。
UIImageView *splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
splashView.image = [UIImage imageNamed:@"Default.png"];
[self.window addSubview:splashView];
[self.window bringSubviewToFront:splashView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:
self.window cache:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:cont ext:)];
splashView.alpha = 0.0;
splashView.frame = CGRectMake(-60, -85, 440, 635);
 [UIView commitAnimations];
 
41、将EGO主题色添加到xcode中 打开终端,执行以下命令
Shell代码
1. mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; 2. cd ~/Library/Application\ Support/Xcode/Color\ Themes;
3. curl -O http://developers.enormego.com/assets/egotheme/
EGO.xccolortheme
然后,重启Xcode,选择Preferences > Fonts & Colors,最后从Color Theme 中选择EGO即可。
 
42、将图片保存到图片库中
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject]; 
if ([touch tapCount]== 1)
{
UIImageWriteToSavedPhotosAlbum([ANImageView image], nil, nil, nil);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照⽚片 message:@"您已将照⽚存于图片库中,打开照片程序即可查" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
 
[alert show];
[alert release];
}
 
43、读取plist文件
//取得文件路径
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"文件
名" ofType:@"plist"];
//读取到一个字典
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//读取到一个数组
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
 
44、使用#pragma mark 加上这样的标识后,在导航条上会显示源文件上方法列表,这样就可对功能相关的方法进行分隔,方便查看了。
设置UITabBarController默认的启动Item //a tabBar
UITabBarController *tabBarController = [[UITabBarController alloc] init];
NSArray *controllers = [NSArray arrayWithObjects: nav1, nav2, nav3, nav4, nil];
tabBarController.viewControllers = controllers; tabBarController.selectedViewController = nav2;
 
45、NSUserDefaults的使用
NSUserDefaults *store = [NSUserDefaults standardUserDefaults]; 
NSUInteger selectedIndex = 1;
[store setInteger:selectedIndex forKey:@"selectedIndex"];
if ([store valueForKey:@"selectedIndex"] != nil) {
NSInteger index = [store integerForKey:@"selectedIndex"]; 
NSLog(@"⽤用户已经设置的selectedIndex的值是:%d", index);
else { 
NSLog(@"请设置默认的值");
}
 
46、更改Xcode的缺省公司名 在终端中执行以下命令:
defaults write com.apple.Xcode PBXCustomTemplateMacroDefiniti ons '{"ORGANIZATIONNAME" = "COMPANY";}'
 
47、设置uiView,成圆角矩形 画个圆角的矩形没啥难的,有两种方法:
1 。直接修改view的样式,系统提供好的了:
view.layer.cornerRadius = 6;
view.layer.masksToBounds = YES; 用layer做就可以了,十分简单。这个需要倒库 QuartzCore.framework;
2. 在view 里面画圆角矩形 CGFloat radius = 20.0;
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1);
CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx =
CGRectGetMaxX(rect);
CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy =
CGRectGetMaxY(rect);
CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFill);
用画笔的方法,在drawRect里面做。
 
48、画图时图片倒转解决方法
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1, -1);
drawImage = [UIImage imageNamed:@"12.jpg"];
CGImageRef image = CGImageRetain(drawImage.CGImage);
CGContextDrawImage(context, CGRectMake(30.0, 200, 450, 695), image); CGContextRestoreGState(context);
 
49、Nsstring 自适应文本宽高度
CGSize feelSize = [feeling sizeWithFont:[UIFont systemFontOfSize:12]
constrainedToSize:CGSizeMake(190, 200)];
float feelHeight = feelSize.height;
 
50、用HTTP协议,获取www.baidu.com网站的HTML数据:
[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]];
 
51、viewDidLoad中设置按钮图案
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, 60, 30);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
 
UIImage *buttonImageNormal = [UIImage imageNamed:@"huifu-001.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal
stretchableImageWithLeftCapWidth:12 topCapHeight:0];
 [button setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; UIImage *buttonImagePressed = [UIImage imageNamed:@"qyanbuhuifu-001.png"];
UIImage *stretchableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 
[button setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];
52、键盘上的return键改成Done: textField.returnKeyType = UIReturnKeyDone;
 
53、textfield设置成为密码框: [textField_pwd setSecureTextEntry:YES];
 
54、收回键盘: [textField resignFirstResponder]; 或者 [textfield addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditin gDidEndOnExit];
55、振动:
#import<AudioToolbox/AudioToolbox.h> //需加头文件
方法一: AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
方法二: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 当设备不支持方法一函数时,起蜂鸣作用, 而方法二支持所有设备
 
56、用Cocoa删除文件:
NSFileManager *defaultManager = [NSFileManager defaultManager]; 
[defaultManager removeFileAtPath: tildeFilename  handler: nil];
 
57、UIView透明渐变与移动效果:
//动画配制开始
[UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:2.5];
//图片上升动画
CGRect rect = imgView.frame ;
rect.origin.y = 30;
imgView.frame = rect;
//半透明度渐变动画
imgView.alpha = 0;
//提交动画
[UIView commitAnimations];
 
58、在UIView的drawRect方法内,用Quartz2D API绘制一个像素宽的水平直线: 
-(void)drawRect:(CGRect)rect{
//获取图形上下文
CGContextRef context = UIGraphicsGetCurrentContext(); //设置图形上下文的路径绘制颜色 CGContextSetStrokeColorWithColor(context, [UIColor
whiteColor].CGColor); //取消防锯齿
CGContextSetAllowsAntialiasing(context, NO); //添加线
CGContextMoveToPoint(context, 50, 50); 
CGContextAddLineToPoint(context, 100, 50); //绘制
CGContextDrawPath(context, kCGPathStroke); }
 
59、用UIWebView加载: www.baidu.com
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[web loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:web]; 
[web release];
 
60、利用UIImageView实现动画:
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *fishAni=[[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
[self.view addSubview:fishAni];
 [fishAni release];
//设置动画帧
fishAni.animationImages=[NSArray arrayWithObjects: [UIImage imageNamed:@"1.jpg"],
[UIImage imageNamed:@"2.jpg"],
[UIImage imageNamed:@"3.jpg"],
[UIImage imageNamed:@"4.jpg"],
[UIImage imageNamed:@"5.jpg"],nil ];
//设置动画总时间 fishAni.animationDuration=1.0;
//设置重复次数,0表示不重复 fishAni.animationRepeatCount=0;
//开始动画
[fishAni startAnimating]; }
 
61、用NSTimer做一个定时器,每隔1秒执行一次 pressedDone; 
-(IBAction)clickBtn:(id)sender{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printHello) userInfo:nil repeats:YES]; 
[timer fire];
 }
 
62、利用苹果机里的相机进行录像:
-(void) choosePhotoBySourceType: (UIImagePickerControllerCameraCaptureMode) sourceType {
m_imagePickerController = [[[UIImagePickerController alloc] init] autorelease];
m_imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
m_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; m_imagePickerController.cameraDevice =UIImagePickerControllerCameraDeviceFront; 
//m_imagePickerController.cameraCaptureMode =UIImagePickerControllerCameraCaptureModeVideo;
NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:m_imagePickerController.sourceType];
if ([sourceTypes containsObject:(NSString *)kUTTypeMovie ]) {
m_imagePickerController.mediaTypes= [NSArray arrayWithObjects: (NSString *)kUTTypeMovie,(NSString *)kUTTypeImage,nil];
}
// m_imagePickerController.cameraCaptureMode = sourceType; //m_imagePickerController.mediaTypes //imagePickerController.allowsEditing = YES;
[self presentModalViewController: m_imagePickerController animated:YES];
 }
 
-(void) takePhoto {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[self choosePhotoBySourceType:nil];
} }
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *takePhoto = [UIButton
buttonWithType:UIButtonTypeRoundedRect];
[takePhoto setTitle:@"录像" forState:UIControlStateNormal];
 [takePhoto addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside]; 
takePhoto.frame = CGRectMake(50,100,100,30); [self.view addSubview:takePhoto];
}
63、App中调用 iPhone的home + 电源键截屏功能 
// 前置声明是消除警告
CGImageRef UIGetScreenImage();
CGImageRef img = UIGetScreenImage();
UIImage* scImage=[UIImage imageWithCGImage:img]; UIImageWriteToSavedPhotosAlbum(scImage, nil, nil, nil);
 
64、切割图片的方法
//切割图片
UIImage *image = [UIImage imageNamed:@"7.jpg"];
//设置需要截取的⼤大⼩小
CGRect rect = CGRectMake(20, 50, 280, 200);
//转换
CGImageRef imageRef = image.CGImage;
//截取函数
CGImageRef imageRefs = CGImageCreateWithImageInRect(imageRef, rect); 
//生成uIImage
UIImage *newImage = [[UIImage alloc] initWithCGImage:imageRefs]; 
//添加到imageView中
imageView = [[UIImageView alloc] initWithImage:newImage]; 
imageView.frame = rect;
 
65、如何屏蔽父view的touch事件
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path,NULL,0,0);
CGRect rect = CGRectMake(0, 100, 320, 40); CGPathAddRect(path, NULL, rect); if(CGPathContainsPoint(path, NULL, point, NO)) {
[self.superview touchesBegan:nil withEvent:nil]; }
CGPathRelease(path);
return self; 
}
 
66、用户按home键推送通知
UIApplication *app = [UIApplication sharedApplication]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pressHome:) name:UIApplicationDidEnterBackgroundNotification object:app];
-(void)pressHome:(NSNotification *)notification {
NSLog(@"pressHome..."); 
}
 
67、在UIImageView中旋转图像:
float rotateAngle = M_PI; //M_PI为一角度
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateA ngle);
imageView.transform = transform;
 
68、隐藏状态栏:
方法一, [UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]; 
方法二, 在应用程序的Info.plist 文件中将 UIStatusBarHidden 设置为YES; 
 
69、构建多个可拖动视图:
@interface DragView: UIImageView{
CGPoint startLocation;
NSString *whichFlower; }
@property (nonatomic ,retain)NSString *whichFlower; @end
@implementation DragView
@synthesize whichFlower;
 
- (void) touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event{ CGPoint pt = [[touhes anyObject ] locationInView:self]; startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet *)touches withEvent:( UIEvent *)event{
CGPoint pt = [[touches anyObject] locatonInView:self]; CGRect frame = [self frame];
frame.origin.x += pt.x – startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame]; }
@end
@interface TestController :UIViewController{
UIView *contentView;
}
@end
@implementation TestController
#define MAXFLOWERS 16
CGPoint randomPoint(){ 
return CGPointMake(random()%6 , random()96);
}
- (void)loadView{
CGRect apprect = [[UIScreen mainScreen] applicationFrame]; 
contentView = [[UIView alloc] initWithFrame :apprect]; 
contentView.backgroundColor = [UIColor blackColor]; 
self.view = contentView;
[contentView release];
for(int i=0 ; i<MAXFLOWERS; i++){
CGRect dragRect = CGRectMake(0.0f ,0.0f, 64.0f ,64.0f); 
dragRect.origin = randomPoint();
DragView *dragger = [[DragView alloc] initWithFrame:dragRect];
 [dragger setUserInteractionEnabled: YES];
NSString *whichFlower = [[NSArray arrayWithObjects:@”blueFlower.png”,@”pinkFlower.png”,nil] objectAtIndex: ( random() %2)];
[dragger setImage:[UIImage imageNamed:whichFlower]]; 
[contentView addSubview :dragger];
[dragger release];
} }
- (void)dealloc{
 [contentView release];
[super dealloc]; 
}
@end
 
70、iPhone中加入dylib库
加入dylib库时,必须在info中加入头文件路径。/usr/include/库名(不要后缀)
 
71、iPhone iPad 中App名字如何支持多语言和显示自定义名字
建立InfoPlist.strings,本地化此文件,然后在文件内添加: CFBundleDisplayName = "xxxxxxxxxxx"; //
这样应⽤用程序就能显示成设置的名字“xxxxxxxxxxx”. 
 
 
72、在数字键盘上添加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 description] hasPrefix:@"<UIKeyboard"] == YES) 
[keyboard addSubview:doneButton];
}
73、去掉iPhone应用图标上的弧形高光 有时候我们的应用程序不需要在图标上加上默认的高光,可以在你的应用的 Info.plist中加入:
Icon already includes gloss effects YES
 
74、实现修改navigation的back按钮 
self.navigationItem.backBarButtonItem =
[[[UIBarButtonItem alloc] initWithTitle: NSLocalizedStringFromTable (@"返回", @"System", nil) style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];
 
75、给图片加上阴影
UIImageView*pageContenterImageView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"onePageApple.png"]];
//添加边框
CALayer*layer = [pageContenterImageView layer];
layer.borderColor= [[UIColor whiteColor]CGColor];
layer.borderWidth=0.0f;
//添加四个边阴影
pageContenterImageView.layer.shadowColor= [UIColor blackColor].CGColor;
pageContenterImageView.layer.shadowOffset=CGSizeMake(0,0); pageContenterImageView.layer.shadowOpacity=0.5; pageContenterImageView.layer.shadowRadius=5.0; 阴影渲染会严重消耗内存 ,导致程序咔叽.
/*阴影效果*/
//添加边框
CALayer*layer = [self.pageContenter layer];
layer.borderColor= [[UIColorwhiteColor]CGColor];
layer.borderWidth=0.0f;
//添加四个边阴影
self.pageContenter.layer.shadowColor= [UIColorblackColor].CGColor;//阴影颜色
self.pageContenter.layer.shadowOffset=CGSizeMake(0,0);//阴影偏移 self.pageContenter.layer.shadowOpacity=0.5;//阴影不透明度 self.pageContenter.layer.shadowRadius=5.0;//阴影半径
⼆二、给视图加上阴影
UIView * content=[[UIView alloc] initWithFrame:CGRectMake(100, 250, 503, 500)];
content.backgroundColor=[UIColor orangeColor];
//content.layer.shadowOffset=10;
content.layer.shadowOffset = CGSizeMake(5, 3); content.layer.shadowOpacity = 0.6; content.layer.shadowColor = [UIColor blackColor].CGColor;
[self.window addSubview:content]; 
 
76、UIView有一个属性,clipsTobounds 默认情况下是NO, 如果,我们想要view2把超出的那部份隐藏起来的话,就得改变它的父视图也 就view1的clipsTobounds属性值。
view1.clipsTobounds = YES;
使用objective-c 建立UUID UUID是128位的值,它可以保证唯一性。通常,它是由机器本身网卡的MAC地
址和当前系统时间来生成的。 UUID是由中划线连接而成的字符串。例如:0A326293-BCDD-4788-8F2D-
C4D8E53C108B
在声明文件中声明一个方法:
#import <UIKit/UIKit.h>
@interface UUIDViewController : UIViewController { }
- (NSString *) createUUID;
@end
对应的实现文件中实现该方法:
- (NSString *) createUUID {
CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidStr = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
CFRelease(uuidObject);
return uuidStr; }
 
77、iPhone iPad中横屏显示代码 
1、强制横屏
[application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
2、在infolist⾥里⾯面加了Supported interface orientations这⼀一项,增加之后添加四个item就是 ipad的四个⽅方向
item0 UIInterfaceOrientationLandscapeLeft
item1 UIInterfaceOrientationLandscapeRight 这表明只⽀支持横屏显⽰示 经常让人混淆迷惑的问题 - 数组和其他集合类
 
78、当一个对象被添加到一个array, dictionary, 或者 set等这样的集合类型中的时候,集合会retain它。 对应 的,当集合类被release的时候,它会发送对应的release消息给包含在其中的对象。 因此,如果你想建立一 个包含一堆number的数组,你可以像下面示例中的几个方法来做
NSMutableArray *array; int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [NSNumber numberWithInt: i];
[array addObject: n]; }
在这种情况下, 我们不需要retain这些number,因为array将替我们这么做。 NSMutableArray *array;
int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [[NSNumber alloc] initWithInt: i];
 [array addObject: n];
[n release];
}
在这个例子中,因为你使用了-alloc去建立了一个number,所以你必须显式的-release它,以保证retain count的平衡。因为将number加入数组的时候,已经retain它了,所以数组中的number变量不会被release
 
79、UIView动画停止调用方法遇到的问题
在实现UIView的动画的时候,并且使⽤用UIView来重复调⽤用它结束的回调时候要 注意以下⽅方法中的finished参数
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if([finishied boolValue] == YES)
//一定要判断这句话,要不在程序中当多个View刷新的时候,就可能出现动画异常的现象 {
//执行想要的动作 }
}
 
80、判断在UIViewController中,viewWillDisappear的时候是push还是 pop出来
- (void)viewWillDisappear:(BOOL)animated {
NSArray *viewControllers = self.navigationController.viewControllers; if (viewControllers.count > 1 && [viewControllers
objectAtIndex:viewControllers.count-2] == self) {
// View is disappearing because a new view controller was pushed onto the
stack
NSLog(@"New view controller was pushed");
} else if ([viewControllers indexOfObject:self] == NSNotFound) { // View is disappearing because it was popped from the stack NSLog(@"View controller was popped");
} }
 
81、连接字符串小技巧
NSString *string1 = @"abc / cde";
NSString *string2 = @"abc" @"cde";
NSString *string3 = @"abc" "cde";
NSLog( @"string1 is %@" , string1 ); 
NSLog( @"string2 is %@" , string2 ); NSLog( @"string3 is %@" , string3 ); 
打印结果如下:
string1 is abc cde string2 is abccde
 
82、随文字大小label自适应
label=[[UILabel alloc] initWithFrame:CGRectMake(50, 23, 175, 33)];
label.backgroundColor = [UIColor purpleColor];
[label setFont:[UIFont fontWithName:@"Helvetica" size:30.0]]; 
[label setNumberOfLines:0];
//[myLable setBackgroundColor:[UIColor clearColor]]; [self.window addSubview:label];
NSString *text = @"this is ok";
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30.0];
CGSize size = [text sizeWithFont: font constrainedToSize: CGSizeMake(175.0f, 2000.0f) lineBreakMode: UILineBreakModeWordWrap];
CGRect rect= label.frame; rect.size = size;
[label setFrame: rect]; [label setText: text];
 
83、UILabel字体加粗
//加粗
lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; //加粗并且倾斜
lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];
 
84、为IOS应用组件添加圆角的方法 具体的实现是使用QuartzCore库,下面我具体的描述一下实现过程:
• 首先创建一个项目,名字叫:ipad_webwiew
• 利⽤用Interface Builder添加⼀一个UIWebView,然后和相应的代码相关联 • 添加QuartzCore.framework
代码实现: 头⽂文件:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface ipad_webwiewViewController : UIViewController {
IBOutlet UIWebView *myWebView; UIView *myView;
}
@property (nonatomic,retain) UIWebView *myWebView; @end
代码实现:
- (void)viewDidLoad {
[super viewDidLoad]; //给图层添加背景图⽚片: //myView.layer.contents = (id)[UIImage
imageNamed:@"view_BG.png"].CGImage; //将图层的边框设置为圆脚
myWebView.layer.cornerRadius = 8; myWebView.layer.masksToBounds = YES; //给图层添加⼀一个有⾊色边框
myWebView.layer.borderWidth = 5; myWebView.layer.borderColor = [[UIColor colorWithRed:0.52
green:0.09 blue:0.07 alpha:1] CGColor]; }
 
85、实现UIToolBar的自动消失 
-(void)showBar
{
! [UIView beginAnimations:nil context:nil];
! [UIView setAnimationDuration:0.40];
! (_toolBar.alpha == 0.0) ? (_toolBar.alpha = 1.0) : (_toolBar.alpha = 0.0);
! [UIView commitAnimations];
}
- (void)viewDidAppear:(BOOL)animated {
[NSObject cancelPreviousPerformRequestsWithTarget: self];
[self performSelector: @selector(delayHideBars) withObject: nil afterDelay: 3.0];
}
- (void)delayHideBars { [self showBar];
}
 
86、自定义UINavigationItem.rightBarButtonItem
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"remote",@"mouse",@"text",nil]];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"home_a.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"myletv_a.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(0, 0, 200, 30); 
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:self action:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem; 
[segmentedControl release];
UINavigationController直接返回到根viewController
 [self.navigationController popToRootViewControllerAnimated:YES];
想要从第五层直接返回到第二层或第三层,用索引的形式
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 2)] animated:YES];
 
87、键盘监听事件
#ifdef __IPHONE_5_0
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 5.0)
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
#endif
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
-(void)keyboardWillShow:(NSNotification *)notification {
NSValue *value = [[notification userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
CGRect keyboardRect = [value CGRectValue]; NSLog(@"value %@ %f",value,keyboardRect.size.height); [UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
keyboardHeight = keyboardRect.size.height; self.view.frame = CGRectMake(0, -(251 - (480 - 64 -
keyboardHeight)), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations]; }
 
88、 ios6.0强制横屏的方法:
在appDelegate里调用
if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
        [[UIApplication sharedApplication]
setStatusBarOrientation:
UIInterfaceOrientationLandscapeRight animated:NO];
    }
上一篇:CSA 第五届研讨会 想象


下一篇:什么是web service