iPhone開發(fā)常用代碼集錦
iPhone開發(fā)常用代碼集錦是本文要介紹的內(nèi)容,主要是來(lái)學(xué)習(xí)iphone開發(fā)中的一些小實(shí)例的實(shí)現(xiàn),具體參考本文詳細(xì)內(nèi)容講解,一起來(lái)看內(nèi)容。
更改cell選中的背景
- UIView *myview = [[UIView alloc] init];
- myview.frame = CGRectMake(0, 0, 320, 47);
- myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
- cell.selectedBackgroundView = myview;
在數(shù)字鍵盤上添加button:
- //定義一個(gè)消息中心
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
- //addObserver:注冊(cè)一個(gè)觀察員 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];//返回應(yīng)用程序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];
- }
- }
正則表達(dá)式使用:
被用于正則表達(dá)式的字串必須是可變長(zhǎng)的,不然會(huì)出問題
將一個(gè)空間放在視圖之上
- [scrollView insertSubview:searchButton aboveSubview:scrollView];
從本地加載圖片
- NSString *boundle = [[NSBundle mainBundle] resourcePath];
- [web1 loadHTMLString:[NSString stringWithFormat:@"<img src='0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];
從網(wǎng)頁(yè)加載圖片并讓圖片在規(guī)定長(zhǎng)寬中縮小
- [cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='%@' height='90px' width='90px'></body></html>",
- goodsInfo.GoodsImg] baseURL:nil];
將網(wǎng)頁(yè)加載到webview上通過javascript獲取里面的數(shù)據(jù),如果只是發(fā)送了一個(gè)連接請(qǐng)求獲取到源碼以后可以用正則表達(dá)式進(jìn)行獲取數(shù)據(jù)
- 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轉(zhuǎn)換成unicode
- utf8Str //
- NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
View自己調(diào)用自己的方法:
- [self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黃色段為方法名,和延遲幾秒執(zhí)行.
顯示圖像:
- CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
- UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
- [myImage setImage:[UIImage imageNamed:@"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];
顯示網(wǎng)絡(luò)活動(dòng)狀態(tài)指示符
這是在iPhone左上部的狀態(tài)欄顯示的轉(zhuǎn)動(dòng)的圖標(biāo)指示有背景發(fā)生網(wǎng)絡(luò)的活動(dòng)。
- UIApplication* app = [UIApplication sharedApplication];
- app.networkActivityIndicatorVisible = YES;
動(dòng)畫:一個(gè)接一個(gè)地顯示一系列的圖象
- NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"],
- [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil];
- UIImageView *myAnimatedView = [UIImageView alloc];
- [myAnimatedView initWithFrame:[self bounds]];
- myAnimatedView.animationImages = myImages; //animationImages屬性返回一個(gè)存放動(dòng)畫圖片的數(shù)組
- myAnimatedView.animationDuration = 0.25; //瀏覽整個(gè)圖片一次所用的時(shí)間
- myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 動(dòng)畫重復(fù)次數(shù)
- [myAnimatedView startAnimating];
- [self addSubview:myAnimatedView];
- [myAnimatedView release];
動(dòng)畫:顯示了something在屏幕上移動(dòng)。注:這種類型的動(dòng)畫是“開始后不處理” -你不能獲取任何有關(guān)物體在動(dòng)畫中的信息(如當(dāng)前的位置) 。如果您需要此信息,您會(huì)手動(dòng)使用定時(shí)器去調(diào)整動(dòng)畫的X和Y坐標(biāo)
這個(gè)需要導(dǎo)入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//拖動(dòng)項(xiàng)目
- Here's how to create a simple draggable image.//這是如何生成一個(gè)簡(jiǎn)單的拖動(dòng)圖象
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 檢索接觸點(diǎn)
- 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 相對(duì)以前的觸摸點(diǎn)進(jìn)行移動(dòng)
- 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 image and add it to your view
- //實(shí)例這個(gè)新的類,放到你需要新的圖片放到你的視圖上
- dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
- [dragger setImage:[UIImage imageNamed:@"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 }
- }
小結(jié):iPhone開發(fā)常用代碼集錦的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對(duì)你 有所幫助!