天天看點

iphone開發筆記

<a>退回輸入鍵盤</a>

  - (BOOL)textFieldShouldReturn:(id)textField{

    [textField resignFirstResponder];

}

<a>CGRect</a>

CGRect frame = CGRectMake (origin.x,origin.y, size.width, size.height);矩形

NSStringFromCGRect(someCG) 把CGRect結構轉變為格式化字元串;

CGRectFromString(aString) 由字元串恢複出矩形;

CGRectInset(aRect) 建立較小或較大的矩形(中心點相同),+較小  -較大

CGRectIntersectsRect(rect1, rect2) 判斷兩矩形是否交叉,是否重疊

CGRectZero 高度和寬度為零的/位于(0,0)的矩形常量

<a>CGPoint &amp; CGSize</a>

CGPoint aPoint = CGPointMake(x, y);  

CGSize aSize = CGSizeMake(width, height);

<a>設定透明度</a>

[myView setAlpha:value];   (0.0 &lt; value &lt; 1.0)

<a>設定背景色</a>

[myView setBackgroundColor:[UIColorredColor]]; 

 (blackColor;darkGrayColor;lightGrayColor;

whiteColor;grayColor;redColor; greenColor;

blueColor;cyanColor;yellowColor;

magentaColor;orangeColor;purpleColor;

brownColor; clearColor;)

<a>自定義顔色</a>

UIColor *newColor = [[UIColor alloc]

 initWithRed:(float) green:(float) blue:(float)alpha:(float)]; 

     0.0~1.0

<a>豎屏</a>

320X480

<a>橫屏</a>

480X320   

20 像素  

44像素

<a>隐藏狀态欄</a>

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

[[UIApplication shareApplication]

setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

<a>螢幕變動檢測</a>

orientation ==UIInterfaceOrientationLandscapeLeft

<a>全屏</a>

window=[[UIWindow alloc] initWithFrame:[UIScreenmainScreen] bounds];

<a>自動适應父視圖大小:</a>

aView.autoresizingSubviews = YES;

aView.autoresizingMask =(UIViewAutoresizingFlexibleWidth |

                                      UIViewAutoresizingFlexibleHeight);

UIButton *scaleUpButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

[scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal];

scaleUpButton.frame = CGRectMake(40, 420,100, 40);

[scaleUpButton addTarget:self

 action:@selector(scaleUp)

forControlEvents:UIControlEventTouchUpInside];

<a>設定視圖背景圖檔</a>

UIImageView *aView;

[aView setImage:[UIImageimageNamed:@”name.png”]];

view1.backgroundColor = [UIColorcolorWithPatternImage:

[UIImageimageNamed:@"image1.png"]];

自定義UISlider的樣式和滑塊

我們使用的是UISlider的setMinimumTrackImage,和setMaximumTrackImage方法來定義圖檔的,這兩個方法可以設定滑塊左邊和右邊的圖檔的,不過如果用的是同一張圖檔且寬度和控件寬度基本一緻,就不會有變形拉伸的後果,先看代碼,寫在 viewDidLoad中:

   //左右軌的圖檔

   UIImage *stetchLeftTrack= [UIImageimageNamed:@"brightness_bar.png"];

   UIImage *stetchRightTrack = [UIImageimageNamed:@"brightness_bar.png"];

   //滑塊圖檔

   UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];

   UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320,257, 7)];

   sliderA.backgroundColor = [UIColor clearColor];

   sliderA.value=1.0;

   sliderA.minimumValue=0.7;

   sliderA.maximumValue=1.0;

   [sliderA setMinimumTrackImage:stetchLeftTrackforState:UIControlStateNormal];

   [sliderA setMaximumTrackImage:stetchRightTrackforState:UIControlStateNormal];

   //注意這裡要加UIControlStateHightlighted的狀态,否則當拖動滑塊時滑塊将變成原生的控件

   [sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted];

   [sliderA setThumbImage:thumbImage forState:UIControlStateNormal];

   //滑塊拖動時的事件

   [sliderA addTarget:self action:@selector(sliderValueChanged:)forControlEvents:UIControlEventValueChanged];

   //滑動拖動後的事件

   [sliderA addTarget:self action:@selector(sliderDragUp:)forControlEvents:UIControlEventTouchUpInside];

   [self.view addSubview:sliderA];

為了大家實驗友善,我附上背景圖brightness_bar.png和滑塊圖mark.png

<a href="http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png">http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png</a>

<a href="http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png">http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png</a>

 -(IBAction)sliderValueChanged:(id)sender{

UISlider *slider = (UISlider *) sender;

NSString *newText = [[NSString alloc]initWithFormat:@”%d”, (int)(slider.value + 0.5f)];

label.text = newText;

<a>活動表單</a>

&lt;UIActionSheetDelegate&gt;

 - (IBActive) someButtonPressed:(id)sender

{

    UIActionSheet *actionSheet =[[UIActionSheet alloc] 

                   initWithTitle:@”Are you sure?”

                   delegate:self

                   cancelButtonTitle:@”No way!”

                   destructiveButtonTitle:@”Yes, I’m Sure!”

                   otherButtonTitles:nil];

    [actionSheetshowInView:self.view];

    [actionSheet release];

 &lt;UIAlertViewDelegate&gt;

 - (void) actionSheet:(UIActionSheet *)actionSheetdidDismissWithButtonIndex:(NSInteger) buttonIndex

     if(buttonIndex !=[actionSheet cancelButtonIndex])

     {

          NSString*message = [[NSString alloc] initWithFormat:@”You can         

                  breathe easy, everything went OK.”];

         UIAlertView *alert = [[UIAlertView alloc]    

                             initWithTitle:@”Something was done”

                              message:message

                              delegate:self

                              cancelButtonTitle:@”OK”

                              otherButtonTitles:nil];

          [alertshow];

          [alertrelease];

          [messagerelease];

     }

<a>動畫效果</a>

-(void)doChange:(id)sender

if(view2 == nil)

[self loadSec];

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:1];       

[UIView setAnimationTransition:([view1superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.viewcache:YES];

    if([view1 superview]!= nil)

[view1 removeFromSuperview];

[self.view addSubview:view2];

}else {

[view2 removeFromSuperview];

[self.view addSubview:view1];

[UIView commitAnimations];

Table View  &lt;UITableViewDateSource&gt;

#pragma mark -

#pragma mark Table View Data Source Methods

//指定分區中的行數,預設為1

- (NSInteger)tableView:(UITableView*)tableView 

 numberOfRowsInSection:(NSInteger)section

return [self.listData count];

//設定每一行cell顯示的内容

- (UITableViewCell *)tableView:(UITableView*)tableView 

cellForRowAtIndexPath:(NSIndexPath*)indexPath

static NSString *SimpleTableIndentifier =@"SimpleTableIndentifier";

UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:SimpleTableIndentifier];

if (cell == nil) {

cell = [[[UITableViewCell alloc] 

initWithStyle:UITableViewCellStyleSubtitle 

reuseIdentifier:SimpleTableIndentifier] 

autorelease];

     UIImage *image =[UIImage imageNamed:@"13.gif"];

cell.imageView.image = image;

NSUInteger row = [indexPath row];

cell.textLabel.text = [listDataobjectAtIndex:row];

     cell.textLabel.font =[UIFont boldSystemFontOfSize:20];

     if(row &lt; 5)

cell.detailTextLabel.text = @"Bestfriends";

else 

    cell.detailTextLabel.text =@"friends";

return cell;

<a>圖像、文本标簽和詳細文本标簽</a>

圖像:如果設定圖像,則它顯示在文本的左側;文本标簽:這是單元的主要文本(UITableViewCellStyleDefault 隻顯示文本标簽);詳細文本标簽:這是單元的輔助文本,通常用作解釋性說明或标簽

UITableViewCellStyleSubtitle

UITableViewCellStyleDefault

UITableViewCellStyleValue1

UITableViewCellStyleValue2

&lt;UITableViewDelegate&gt;

#pragma mark Table View Delegate Methods

//把每一行縮進級别設定為其行号

- (NSInteger)tableView:(UITableView*)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath

return row;

//擷取傳遞過來的indexPath值

- (NSIndexPath *)tableView:(UITableView*)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath

if (row == 0) 

return nil;

return indexPath;

- (void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath

NSString *rowValue = [listDataobjectAtIndex:row];

NSString *message = [[NSString alloc]initWithFormat:@"You selected %@",rowValue];

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Row Selected"

message:message

    delegate:nil

  cancelButtonTitle:@"Yes, Idid!"

  otherButtonTitles:nil];

[alert show];

[alert release];

[message release];

[tableView deselectRowAtIndexPath:indexPathanimated:YES];

//設定行的高度

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

return 40;

NavigationController 推出push 推出pop

[self.navigationControllerpushViewController:_detailController animated:YES];

[self.navigationControllerpopViewControllerAnimated:YES];

Debug:

NSLog(@"%s %d", __FUNCTION__,__LINE__);

點選textField外的地方回收鍵盤

先定義一個UIControl類型的對象,在上面可以添加觸發事件,令SEL實踐為回收鍵盤的方法,最後将UIControl的執行個體加到目前View上。

UIControl *m_control = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];

[m_control addTarget:selfaction:@selector(keyboardReturn)

[self.view addSubview:m_control];

- (void) keyboardReturn

[aTextField resignFirstResponder];

當鍵盤調出時将輸入框覆寫時,可以用下方法:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField

[self.view setFrame:CGRectMake(0, -100,320, 480) ];

return YES;

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField

  [self.view setFrame:CGRectMake(0, 0, 320,480)];

           return YES;

當準備輸入時,将視圖的位置上調100,這樣鍵盤就不能覆寫到輸入框。

當依賴注入方法不好使時,可以在AppDelegate内申明一個全局的控制器執行個體_anotherViewController,在另一個需要使用_anotherViewController的地方定義以下委托方法,使用共享的UIApplication執行個體來擷取該委托的引用

SomeAppDelegate *appDelegate =(SomeAppDelegate *)[[UIApplication sharedApplication] delegate];

_anotherViewController =appDelegate._anotherViewController;

純代碼在UIViewController控制器内建Table View

@interface RootViewController :UIViewController &lt;UITableViewDelegate, UITableViewDataSource&gt; {

NSArray *timeZoneNames;

@property (nonatomic,retain) NSArray*timeZoneNames;

@end

(void) loadView

UITableView *tableView = [[UITableViewalloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] style:UITableViewStylePlain];

tableView.autoresizingMask =(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth);

tableView.delegate = self;

tableView.dataSource = self;

[tableView reloadData];

self.view = tableView;

[tableView release];

NSString *thePath = [[NSBundle mainBundle]pathForResource:@"States" ofType:@"plist"];

NSArray *array = [NSArrayarrayWithContentsOfFile:thePath];

<a>UITouch</a>

手指的觸摸範圍:64X64

#pragma mark Touch Events

- (void)touchesBegan:(NSSet *) toucheswithEvent:(UIEvent *) event {

originFrame = bookCover.frame;

NSLog(@"%s %d",__FUNCTION__,__LINE__);

if ([touches count] == 2)

NSArray *twoTouches = [touches allObjects];

UITouch *firstTouch = [twoTouchesobjectAtIndex:0];

UITouch *secondTouch = [twoTouchesobjectAtIndex:1];

CGPoint firstPoint = [firstTouchlocationInView:bookCover];

CGPoint secondPoint = [secondTouchlocationInView:bookCover];

CGFloat deltaX = secondPoint.x -firstPoint.x;

CGFloat deltaY = secondPoint.y - firstPoint.y;

initialDistance = sqrt(deltaX * deltaX +deltaY * deltaY );

frameX = bookCover.frame.origin.x;

frameY = bookCover.frame.origin.y;

frameW = bookCover.frame.size.width;

frameH = bookCover.frame.size.height;

- (void)touchesMoved:(NSSet *) toucheswithEvent:(UIEvent *) event {

if([touches count] == 2)

CGFloat deltaY = secondPoint.y -firstPoint.y;

CGFloat currentDistance = sqrt(deltaX *deltaX + deltaY * deltaY );

if (initialDistance == 0) {

initialDistance = currentDistance;

else if (currentDistance !=initialDistance)

CGFloat changedDistance = currentDistance -initialDistance;

NSLog(@"changedDistance =%f",changedDistance);

[bookCover setFrame:CGRectMake(frameX -changedDistance / 2,

frameY - (changedDistance * frameH) / (2 *frameW),

frameW + changedDistance,

frameH + (changedDistance * frameH) /frameW)];

- (void)touchesEnded:(NSSet *) toucheswithEvent:(UIEvent *) event {

UITouch *touch = [touches anyObject];

UITouch輕按兩下圖檔變大/還原

if ([touch tapCount] == 2)

if (!flag) {

[bookCoversetFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2,

bookCover.frame.origin.y -bookCover.frame.size.height / 2,

2 * bookCover.frame.size.width,

2 * bookCover.frame.size.height)];

flag = YES;

else {

[bookCoversetFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4,bookCover.frame.origin.y + bookCover.frame.size.height / 4,

bookCover.frame.size.width / 2,bookCover.frame.size.height / 2)];

flag = NO;

<a>Get the Location of Touches</a>

(CGPoint)locationInView:(UIView *)view

(CGPoint)previousLocationInView:(UIView*)view

view window

<a>Getting Touch Attributes</a>

tapCount(read only) timestamp(read only)phase(read only)

Getting a Touch Object's GestureRecognizers

gestureRecognizers

<a>Touch Phase</a>

UITouchPhaseBegan

UITouchPhaseMoved

UITouchPhaseStationary

UITouchPhaseEnded

UITouchPhaseCancelled

NSString *plistPath = [[NSBundlemainBundle] pathForResource:@"book" ofType:@"plist"];

NSDictionary *dictionary = [[NSDictionaryalloc] initWithContentsOfFile:plistPath];

NSString *book = [dictionaryobjectForKey:bookTitle];

[textView setText:book];

(void) initialize {

NSUserDefaults = [NSUserDefaults standardUserDefaults];

NSDictionary *appDefaults = [NSDictionarydictionaryWithObject:@"YES" forKey:@"DeleteBackup"];

[defaults registerDefaults:appDefaults];

To get a value of a default, use thevalueForKey: method:

[[theDefaultsController values] valueForKey:@"userName"];

To set a value for a default, usesetValue:forKey:

[[theDefaultsController values]setValue:newUserName forKey:@"userName"];

[[NSUserDefaults standardUserDefaults]setValue:aVale forKey:aKey];

[[NSUserDefaults standardUserDefaults]valueForKey:aKey];

NSArray *paths =NSSearchPathForDictionariesInDomains(NSDocumentDirectory,

NSUserDomainMask, YES);

NSString *documentsDirectory = [pathsobjectAtIndex:0];

NSString *filename = [documentsDirectory

stringByAppendingPathComponent:@"theFile.txt"];

NSString *tempPath =NSTemporaryDirectory();

NSString *tempFile = [tempPathstringByAppendingPathComponent:@"tempFile.txt"];

[[NSUserDefaults standardUserDefaults]setObject:data forKey:@"someKey"];

[[NSUserDefaults standardUserDefaults] objectForKey:aKey];

自定義NavigationBar

navigationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];

[navigationBarsetBarStyle:UIBarStyleBlackOpaque];

myNavigationItem = [[UINavigationItemalloc] initWithTitle:@"Setting"];

[navigationBar setItems:[NSArrayarrayWithObject:myNavigationItem]];

[self.view addSubview:navigationBar];

backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:selfaction:@selector(back)];

myNavigationItem.leftBarButtonItem =backButton;

NSURL *url = [NSURLURLWithString:@"http://www.cnblogs.com/tracy-e/"];

[[UIApplication sharedApplication]openURL:url];

webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];

[webView setDelegate:self];

[webView setScalesPageToFit:YES];

[webViewsetAutoresizingMask:UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight];

[webView setAllowsInlineMediaPlayback:YES];

[self.view addSubview:webView];

NSString *pdfPath = [[NSBundle mainBundle]pathForResource:@"ojc" ofType:@"pdf"];

NSURL *url = [NSURLfileURLWithPath:pdfPath];

NSURLRequest *request = [NSURLRequestrequestWithURL:url

cachePolicy:NSURLRequestUseProtocolCachePolicy

timeoutInterval:5];

[webView loadRequest:request];

[myWebView loadRequest:[NSURLRequestrequestWithURL:[NSURL

                       URLWithString:@"http://www.cnblogs.com/tracy-e/"]]];

NSString *errorString = [NSStringstringWithFormat:@"&lt;html&gt;&lt;center&gt;&lt;font size=

+5 color ='red'&gt;An ErrorOccurred:&lt;br&gt;%@&lt;/fone&gt;&lt;/center&gt;&lt;/html&gt;",error];

[myWebView loadHTMLString:errorStringbaseURL:nil];

//Stopping a load request when the view isto disappear

- (void)viewWillDisappear:(BOOL)animate{

if ([myWebView loading]){

[myWebView stopLoading];

myWebView.delegate = nil;

[UIApplicationshareApplication].networkActivityIndicatorVisible = NO;

<a>漢字轉碼</a>

NSString *oriString =@"\u67aa\u738b";

NSString *escapedString = [oriString

stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

<a>Checking for background support on earlierversions of iOS</a>

UIDevice *device = [UIDevicecurrentDevice];

BOOL backgroundSupported = NO;

if ([devicerespondsToSelector:@selector(isMultitaskingSupported)]){

backgroundSupported =device.multitaskingSupported;

Being a Responsible,Multitasking-AwareApplication

# Do not make any OpenGL ES calls from yourcode.

# Cancel any Bonjour-related servicesbefore being suspended.

# Be prepared to handle connection failuresin your network-based sockets.

# Save your application state before movingto the background.

# Release any unneeded memory when movingto the background.

# Stop using shared system resources beforebeing suspended.

# Avoid updating your windows and views.

# Respond to connect and disconnectnotification for external accessories.

# Clean up resource for active alerts whenmoving to the background.

# Remove sensitive information from viewsbefore moving to the background.

# Do minimal work while running in thebackground.

<a>Handing the Keyboard notifications</a>

//Call this method somewhere in your viewcontroller setup code

- (void) registerForKeyboardNotifications{

[[NSNotificationCenter defaultCenter]addObserver:self

selector:@selector(keyboardWasShown:)

name:UIKeyboardDidShowNotification

object:nil];

selector:@selector(keyboardWasHidden:)

name:UIKeyboardDidHideNotification

//Called when theUIKeyboardDidShowNotification is sent

- (void)keyboardWasShown:(NSNotification *)aNotification{

if(keyboardShown)

return;

NSDictionary *info = [aNotificationuserInfo];

//get the size of the keyboard.

NSValue *aValue = [infoobjectForKey:UIKeyboardFrameBeginUserInfoKey];

CGSize keyboardSize = [aValueCGRectValue].size;

//Resize the scroll view

CGRect viewFrame = [scrollView frame];

viewFrame.size.height -=keyboardSize.height;

//Scroll the active text field into view

CGRect textFieldRect = [activeField frame];

[scrollViewscrollRectToVisible:textFieldRect animated:YES];

keyboardShown = YES;

//Called when theUIKeyboardDidHideNotification is sent

- (void)keyboardWasHidden:(NSNotification*) aNotification{

//Get the size of the keyboard.

NSValue *aValue = [infoobjectForKey:UIKeyboardFrameEndUserInfoKey];

//Reset the height of the scroll view toits original value

CGRect viewFrame = [scrollView Frame];

viewFrame.size.height +=keyboardSize.height;

scrollView.frame = viewFrame;

keyboardShown = NO;

//首先給不同的textField賦不同的且相鄰的tag值

- (BOOL)textFieldShouldReturn:(UITextField*)textField

if ([textField returnKeyType] !=UIReturnKeyDone)

NSInteger nextTag = [textField tag] + 1;

UIView *nextTextField = [[self tableView]viewWithTag:nextTag];

[nextTextField becomeFirstResponder];

[textField resignFirstResponder];

<a>Configuring a date formatter</a>

- (void)viewDidLoad {

[super viewDidLoad];

dateFormatter = [[NSDateFormatter alloc]init];

[dateFormatter setGeneratesCalendarDates:YES];

[dateFormatter setLocale:[NSLocalecurrentLocale]];

[dateFormatter setCalendar:[NSCalendarautoupdatingCurrentCalendar]];

[dateFormatter setTimeZone:[NSTimeZonedefaultTimeZone]];

[dateFormattersetDateStyle:NSDateFormatterShortStyle];

DOB.placeholder = [NSStringstringWithFormat:@"Example: %@",[dateFormatter stringFromDate:[NSDatedate]]];

- (void)textFieldDidEndEditing:(UITextField*)textField{

if ([textField.textisEqualToString:@""])

switch (textField.tag){

case DOBField:

NSDate *theDate = [dateFormatterdateFromString:textField.text];

if (theDate)

[inputDate setObject:theDateforKey:MyAppPersonDOBKey];

break;

default:

tableView的cell高度除了在delegate中指定外,還可以在任意位置以[tableView setRowHeight:44]的方式指定

[[self navigationItem]setLeftBarButtonItem:[self editButtonItem]];

- (void)setEditing:(BOOL)editinganimated:(BOOL)animated{

[super setEditing:editing animated:animated];

if (editing){

......

else{

One added a subview to a view, release thesubview to avoid the extra retain count of it, Because when you insert a viewas a subview using addSubview:, the subview is retained by its superview. When youremove the subview from its superview using the removeFromSuperview: method,subview is autoreleased.

在iPhone開發中, 有時候我們想給導覽列添加背景圖檔, 實作多樣化的導覽列效果, 用其他方法往往無法達到理想的效果, 經過網上搜尋及多次實驗, 确定如下最佳實作方案:

為UINavigatonBar增加如下Category(類别:提供一種為某個類添加方法而又不必編寫子類的途徑,類别隻能添加成員函數,不能添加資料成員):

@implementation UINavigationBar (CustomImage)  

- (void)drawRect:(CGRect)rect {  

    UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];  

    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  

}  

@end  

例如, 在我的項目中, 添加如下代碼:

/////////////////////////////////////////////////////////  

/* input: The image and a tag to later identify the view */  

    UIImage *image = [UIImage imageNamed: @"title_bg.png"];  

@implementation FriendsPageViewController  

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  

- (void)viewDidLoad {     

    self.navigationBar.tintColor = [UIColor purpleColor];  

    [self initWithRootViewController:[[RegPageViewController alloc] init]];  

    [super viewDidLoad];  

......  

實作的效果如下圖:

轉載,原文位址 http://blog.csdn.net/wave_1102/archive/2009/11/04/4768212.aspx

@implementation UINavigationBar(UINavigationBarCategory) 

- (void)drawRect:(CGRect)rect { 

   //顔色填充 

// UIColor *color = [UIColor redColor]; 

// CGContextRef context = UIGraphicsGetCurrentContext(); 

// CGContextSetFillColor(context, CGColorGetComponents( [colorCGColor])); 

// CGContextFillRect(context, rect); 

// self.tintColor = color; 

   //圖檔填充 

UIColor *color= [UIColor colorWithRed:46.0f/255.0f

green:87.0f/255.0fblue:29.0f/255.0f alpha:1.0f];

   UIImage *img    = [UIImageimageNamed: @"bg.png"]; 

   [img drawInRect:CGRectMake(0, 0, self.frame.size.width,self.frame.size.height)]; 

   self.tintColor = color; 

<a>加載圖檔要及時release</a>

你還在使用myImage = [UIImage imageNamed:@"icon.png"]; 嗎?

如題,是不是大家為了友善都這樣加載圖檔啊

myImage = [UIImageimageNamed:@"icon.png"];

那麼小心了

這種方法在一些圖檔很少,或者圖檔很小的程式裡是ok的。

但是,在大量加載圖檔的程式裡,請千萬不要這樣做。

為什麼呢 ???????

這種方法在applicationbundle的頂層檔案夾尋找由供應的名字的圖象。 如果找到圖檔,裝載到iPhone系統緩存圖象。那意味圖檔是(理論上)放在記憶體裡作為cache的。

試想你圖檔多了,是什麼後果?

圖檔cache極有可能不會響應 memory warnings and releaseits objects

是以,用圖檔的時候一定要小心的alloc和release。

推薦使用 NSString*path = [[NSBundle mainBundle] pathForResource:@"icon"ofType:@"png"];

myImage = [UIImageimageWithContentsOfFile:path];

// Todo use of myImage

[myImage release];

UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0, 55, 320, 300)];

   webView.delegate = self;

   webView.multipleTouchEnabled = YES;

   webView.scalesPageToFit = YES;

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

   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *docPath = [documentsDirectorystringByAppendingString:@"/doc2003_1.doc"];    NSLog(@"#######%@",docPath);

   NSURL *url = [NSURL fileURLWithPath:docPath];

   NSURLRequest *request = [NSURLRequest requestWithURL:url];

   [webView loadRequest:request];

   [self.view addSubview:webView];

[webViewrelease];

有時候在 iPhone 遊戲中,既要播放背景音樂,同時又要播放比如槍的開火音效。此時您可以試試以下方法

    NSString *musicFilePath = [[NSBundlemainBundle] pathForResource:fileName ofType:@"wav"];       //建立音樂檔案路徑

    NSURL *musicURL = [[NSURL alloc]initFileURLWithPath:musicFilePath]; 

    AVAudioPlayer* musicPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];

    [musicURL release];

    [musicPlayer prepareToPlay];

    //[musicPlayer setVolume:1];            //設定音量大小

    //musicPlayer .numberOfLoops = -1;//設定音樂播放次數  -1為一直循環

要導入架構 AVFoundation.framework,頭檔案中 #import &lt;AVFoundation/AVFoundation.h&gt;;做成類的話則更友善。

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(_willBecomeActive)name:UIApplicationDidBecomeActiveNotification object:nil];

LOGO_320×44.png 圖檔顯示在背景上,

@implementation UINavigationBar(UINavigationBarCategory)

- (void)drawRect:(CGRect)rect {

       //加入旋轉坐标系代碼

    // Drawing code      

       UIImage*navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"];

       CGContextRefcontext = UIGraphicsGetCurrentContext();

       CGContextTranslateCTM(context,0.0, self.frame.size.height);

       CGContextScaleCTM(context,1.0, -1.0);    

       CGPointcenter=self.center;

       CGImageRefcgImage= CGImageCreateWithImageInRect(navBarImage.CGImage, CGRectMake(0, 0, 1,44));

       CGContextDrawImage(context,CGRectMake(center.x-160-80, 0, 80, self.frame.size.height), cgImage);

       CGContextDrawImage(context,CGRectMake(center.x-160, 0, 320, self.frame.size.height), navBarImage.CGImage);

       CGContextDrawImage(context,CGRectMake(center.x+160, 0, 80, self.frame.size.height), cgImage);

old code

CGContextDrawImage(context, CGRectMake(0,0, self.frame.size.width, self.frame.size.height), navBarImage.CGImage);

hack 過logo 不再拉伸

<a>清除電話号碼中的其他符号(源碼)</a>

最近從通訊錄讀取電話号碼,讀出得号碼如:134-1814-****。

而我需要的為11位純數字,一直找方法解決此問題,今天終于找到了。。

分享一下……

代碼如下:

NSString *originalString = @"(123)123123 abc";

NSMutableString *strippedString =[NSMutableString

       stringWithCapacity:originalString.length];

NSScanner *scanner = [NSScannerscannerWithString:originalString];

NSCharacterSet *numbers = [NSCharacterSet

       characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO) {

 NSString *buffer;

  if([scanner scanCharactersFromSet:numbers intoString:&amp;buffer]) {

   [strippedString appendString:buffer];

  }

  //--------- Add the following to get out of endless loop

 else {

    [scanner setScanLocation:([scanner scanLocation] + 1)];

 }   

  //--------- End of addition

NSLog(@"%@", strippedString); //"123123123"

<a>正則判斷:字元串隻包含字母和數字</a>

NSString *mystring =@"Letter1234";

NSString *regex =@"[a-z][A-Z][0-9]";

NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];

if ([predicate evaluateWithObject:mystring]== YES) {

    //implement

UITableView 的 cell 預設出現在uitableview 的第一行,如果你想自定義UITableViewCell 與導覽列間距的話,可以使用下面這行代碼

tableview.tableHeaderView= [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)]autorelease];

    UITableview 的滾動條預設顔色是黑色的,如果 UItableview 背景也是深顔色,則滾動條會變的很不明顯。您可以用下面這行代碼來改變滾動條的顔色

self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;

當然,最後的“White”也可以換成其它顔色。

<a>下檔案之前擷取到檔案大小的代碼</a>

下面這段代碼,能實作在下載下傳檔案之前獲得檔案大小,應用在軟體裡,能在很大程度上改善使用者體驗

[m_pASIHTTPRequestsetDidReceiveResponseHeadersSelector:@selector(didReceiveResponseHeaders:)];

-(void)didReceiveResponseHeaders:(ASIHTTPRequest *)request

    NSLog(@"didReceiveResponseHeaders%@",[m_request.responseHeaders valueForKey:@"Content-Length"]);

<a>網絡程式設計總結iphone</a>

一:确認網絡環境3G/WIFI

    1. 添加源檔案和framework

    開發Web等網絡應用程式的時候,需要确認網絡環境,連接配接情況等資訊。如果沒有處理它們,是不會通過Apple的審(我們的)查的。

    Apple 的例程 Reachability 中介紹了取得/檢測網絡狀态的方法。要在應用程式程式中使用Reachability,首先要完成如下兩部:

    1.1. 添加源檔案:

    在你的程式中使用 Reachability 隻須将該例程中的 Reachability.h 和 Reachability.m 拷貝到你的工程中。如下圖:

    1.2.添加framework:

    将SystemConfiguration.framework 添加進工程。如下圖:

    2. 網絡狀态

    Reachability.h中定義了三種網絡狀态:

    typedef enum {

        NotReachable = 0,            //無連接配接

        ReachableViaWiFi,            //使用3G/GPRS網絡

        ReachableViaWWAN            //使用WiFi網絡

    } NetworkStatus;

    是以可以這樣檢查網絡狀态:

    Reachability *r = [ReachabilityreachabilityWithHostName:@“www.apple.com”];

    switch ([r currentReachabilityStatus]) {

            case NotReachable:

                    // 沒有網絡連接配接

                    break;

            case ReachableViaWWAN:

                    // 使用3G網絡

            case ReachableViaWiFi:

                    // 使用WiFi網絡

    }

    3.檢查目前網絡環境

    程式啟動時,如果想檢測可用的網絡環境,可以像這樣

    // 是否wifi

    + (BOOL) IsEnableWIFI {

        return ([[ReachabilityreachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

    // 是否3G

    + (BOOL) IsEnable3G {

        return ([[ReachabilityreachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

    例子:

    - (void)viewWillAppear:(BOOL)animated{   

    if (([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus == NotReachable)&amp;&amp;

           ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus ==NotReachable)) {

            self.navigationItem.hidesBackButton= YES;

            [self.navigationItemsetLeftBarButtonItem:nil animated:NO];

        }

    4. 連結狀态的實時通知

    網絡連接配接狀态的實時檢查,通知在網絡應用中也是十分必要的。接續狀态發生變化時,需要及時地通知使用者:

    Reachability 1.5版本

    // My.AppDelegate.h

    #import "Reachability.h"

    @interface MyAppDelegate : NSObject&lt;UIApplicationDelegate&gt; {

        NetworkStatus remoteHostStatus;

    @property NetworkStatus remoteHostStatus;

    @end

    // My.AppDelegate.m

    #import "MyAppDelegate.h"

    @implementation MyAppDelegate

    @synthesize remoteHostStatus;

    // 更新網絡狀态

    - (void)updateStatus {

        self.remoteHostStatus = [[ReachabilitysharedReachability] remoteHostStatus];

    // 通知網絡狀态

    - (void)reachabilityChanged:(NSNotification*)note {

        [self updateStatus];

        if (self.remoteHostStatus ==NotReachable) {

            UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:NSLocalizedString(@"AppName", nil)

                        message:NSLocalizedString (@"NotReachable", nil)

                        delegate:nilcancelButtonTitle:@"OK" otherButtonTitles: nil];

            [alert show];

            [alert release];

    // 程式啟動器,啟動網絡監視

    -(void)applicationDidFinishLaunching:(UIApplication *)application {

        // 設定網絡檢測的站點

        [[Reachability sharedReachability]setHostName:@"www.apple.com"];

        [[Reachability sharedReachability]setNetworkStatusNotificationsEnabled:YES];

        // 設定網絡狀态變化時的通知函數

        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:)

                                                name:@"kNetworkReachabilityChangedNotification" object:nil];

    - (void)dealloc {

        // 删除通知對象

        [[NSNotificationCenter defaultCenter]removeObserver:self];

        [window release];

        [super dealloc];

    Reachability 2.0版本

    // MyAppDelegate.h

    @class Reachability;

        @interface MyAppDelegate : NSObject&lt;UIApplicationDelegate&gt; {

            Reachability  *hostReach;

    // MyAppDelegate.m

        Reachability* curReach = [note object];

        NSParameterAssert([curReachisKindOfClass: [Reachability class]]);

        NetworkStatus status = [curReachcurrentReachabilityStatus];

        if (status == NotReachable) {

            UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"AppName""

                             message:@"NotReachable"

                              delegate:nil

                             cancelButtonTitle:@"YES" otherButtonTitles:nil];

                              [alert show];

                              [alert release];

        // ...

        // 監測網絡情況

        [[NSNotificationCenter defaultCenter]addObserver:self

                             selector:@selector(reachabilityChanged:)

                              name:kReachabilityChangedNotification

                              object: nil];

        hostReach = [[ReachabilityreachabilityWithHostName:@"www.google.com"] retain];

        hostReach startNotifer];

二:使用NSConnection下載下傳資料

    1.建立NSConnection對象,設定委托對象

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURL URLWithString:[self urlString]]];

    [NSURLConnectionconnectionWithRequest:request delegate:self];

    2. NSURLConnection delegate委托方法

        - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response; 

        - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error; 

        - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data; 

        - (void)connectionDidFinishLoading:(NSURLConnection*)connection; 

    3. 實作委托方法

    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response {

        // store data

        [self.receivedData setLength:0];            //通常在這裡先清空接受資料的緩存

    - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data {

           /* appends the new data to thereceived data */

        [self.receivedDataappendData:data];        //可能多次收到資料,把新的資料添加在現有資料最後

    - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error {

        // 錯誤處理

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection {

        // disconnect

        [UIApplicationsharedApplication].networkActivityIndicatorVisible = NO;  

        NSString *returnString = [[NSStringalloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];

        NSLog(returnString);

        [self urlLoaded:[self urlString]data:self.receivedData];

        firstTimeDownloaded = YES;

三:使用NSXMLParser解析xml檔案

    1. 設定委托對象,開始解析

    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];   //或者也可以使用initWithContentsOfURL直接下載下傳檔案,但是有一個原因不這麼做:

    // It's also possible to have NSXMLParserdownload the data, by passing it a URL, but this is not desirable

    // because it gives less control over thenetwork, particularly in responding to connection errors.

    [parser setDelegate:self];

    [parser parse];

    2. 常用的委托方法

    - (void)parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName

                                namespaceURI:(NSString *)namespaceURI

                               qualifiedName:(NSString *)qName

                               attributes:(NSDictionary *)attributeDict;

    - (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementName

                               namespaceURI:(NSString *)namespaceURI

                               qualifiedName:(NSString *)qName;

    - (void)parser:(NSXMLParser *)parserfoundCharacters:(NSString *)string;

    - (void)parser:(NSXMLParser *)parserparseErrorOccurred:(NSError *)parseError;

    3.  應用舉例

    - (void)parseXMLFileAtURL:(NSURL *)URLparseError:(NSError **)error

    {

        NSXMLParser *parser = [[NSXMLParseralloc] initWithContentsOfURL:URL];

        [parser setDelegate:self];

        [parser setShouldProcessNamespaces:NO];

        [parsersetShouldReportNamespacePrefixes:NO];

        [parser setShouldResolveExternalEntities:NO];

        [parser parse];

        NSError *parseError = [parserparserError];

        if (parseError &amp;&amp; error) {

            *error = parseError;

        [parser release];

    - (void)parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                       qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{

        // 元素開始句柄

        if (qName) {

            elementName = qName;

        if ([elementNameisEqualToString:@"user"]) {

            // 輸出屬性值

            NSLog(@"Name is %@ , Age is%@", [attributeDict objectForKey:@"name"], [attributeDictobjectForKey:@"age"]);

    - (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                       qualifiedName:(NSString *)qName

        // 元素終了句柄

               elementName = qName;

        }

    - (void)parser:(NSXMLParser *)parserfoundCharacters:(NSString *)string

        // 取得元素的text

    NSError *parseError = nil;

    [self parseXMLFileAtURL:[NSURLURLWithString:feedURLString] parseError:&amp;parseError];

iphone裡面要畫圖一般都是通過CoreGraphics.framwork和QuartzCore.framwork實作,apple的官方sdk demon中包含了QuartzCore的基本用法,

折線圖

要實作折線圖也就把全部的點連起來,movePointLineto,具體的調用裡面的api就可以實作了,但是畫坐标就比較麻煩了,裡面需要去轉很多,好在國外有人開源了一個畫折線圖的開發包,首先看看效果吧,具體怎麼用可以參考作者git版本庫中的wiki。

<a href="http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library">http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library</a>

我對源代碼進行簡單的修改,使其顯示坐标之類的,更加符合工程的需要,但是還沒有實作畫多組資料,隻能畫一組資料,不用viewContol,而使用addsubview,直接添加到目前的視窗,最終效果如下。

使用方法:

1.工程添加tk庫裡面的如下檔案

<a href="http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/7_F3J9_RC0SG6U8475PJ.jpg"></a>

2. 添加QuartzCore  framework

#import &lt;QuartzCore/QuartzCore.h&gt;

添加TapkuLibrary.bundle資源檔案

3.代碼中完成執行個體,資料初始化就可以用了

<a href="http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/2TKNVFWV48531GC8TG.jpg"></a>

如果您希望運作自己開發的App時,iPhone的螢幕不再自動變暗,可以使用以下方法讓螢幕常亮: iPhone OS用一個布爾值用來控制是否取消應用程式空閑時間:@property(nonatomic,getter=isIdleTime

如果您希望運作自己開發的App時,iPhone的螢幕不再自動變暗,可以使用以下方法讓螢幕常亮:

  iPhone OS用一個布爾值用來控制是否取消應用程式空閑時間:@property(nonatomic, getter=isIdleTimerDisabled) BOOLidleTimerDisabled。這個值的預設屬性是"NO"。當大多數應用程式沒有接收到使用者輸入資訊的時候,系統會把裝置設定成“休眠”狀态,iPhone螢幕也會變暗。這樣做是為了儲存更多電量。事實上,應用程式在運作加速度遊戲的時候是不需要使用者輸入的,當然這裡隻是一個假設,把這個變量設定為"YES",來取消系統休眠的“空閑時間”。

重點是:你必須當真正需要的時候才打開這個屬性當你不用的時候馬上還願成"NO"。大多數應用程式在休眠時間到的時候讓系統關閉螢幕。這個包括了有音頻的應用程式。在Audio Session Services中使用适當的回放和記錄功能不會被間斷當螢幕關閉時。隻有地圖應用程式,遊戲或者一些不間斷的使用者互動程式可以取消這個屬性。

<a>蘋果開發網絡程式設計知識總結</a>

以下蘋果開發網絡程式設計知識由 CocoaChina 會員 cocoa_yang 總結,希望能為蘋果開發新手梳理知識脈絡,節省入門時間。一:确認網絡環境3G/WIFI 1. 添加源檔案和framework 開發Web等網絡應用程式

  以下蘋果開發網絡程式設計知識由 CocoaChina 會員 “cocoa_yang” 總結,希望能為蘋果開發新手梳理知識脈絡,節省入門時間。

    1. 添加源檔案和framework

    開發Web等網絡應用程式的時候,需要确認網絡環境,連接配接情況等資訊。如果沒有處理它們,是不會通過Apple的審查的。

        NotReachable = 0,            //無連接配接

    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus== NotReachable) &amp;&amp;

            ([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) {

           [alert release];

        [UIApplicationsharedApplication].networkActivityIndicatorVisible = NO; 

                                namespaceURI:(NSString *)namespaceURI

    static NSString *feedURLString =@"http://www.yifeiyang.net/test/test.xml";

        [parsersetShouldResolveExternalEntities:NO];

       NSError *parseError = [parser parserError];

        if ([elementName isEqualToString:@"user"]){

<a>如何隐藏狀态欄</a>

[ UIApplication sharedApplication].statusBarHidden = YES;

.m檔案是object-c檔案

.mm檔案相當于c++或者c檔案

細微差别會導緻程式崩潰。

但是我不太明白為何蘋果要把編譯器做的對這兩種常量有差別。

不過值得一提的是可能為了友善蘋果自身的NSObject對象的格式化輸出。

NSURLCachedoesn't seem to support writing to disk on iPhone. The documentation forNSCachedURLResponse says that the NSURLCacheStoragePolicy"NSURLCacheStorageAllowed" is treated as"NSURLCacheStorageAllowedInMemoryOnly" by iPhone OS.

官方文檔是這麼說的。

為了證明這個,我找到了一個目錄。

/private/var/mobile/Library/Caches/Safari/Thumbnails

<a>随機數的使用</a>

        頭檔案的引用

        #import &lt;time.h&gt;

        #import &lt;mach/mach_time.h&gt;

        srandom()的使用

        srandom((unsigned)(mach_absolute_time()&amp; 0xFFFFFFFF));

        直接使用 random() 來調用随機數

        float rotateAngle = M_PI;

        CGAffineTransform transform=CGAffineTransformMakeRotation(rotateAngle);

        imageView.transform = transform;

        以上代碼旋轉imageView, 角度為rotateAngle, 方向可以自己測試哦!

        UIImageView *imageView = [[UIImageViewalloc] initWithImage:[UIImage imageNamed:@"bg.png"]];

        imageView.layer.anchorPoint =CGPointMake(0.5, 1.0);

        這個是把旋轉點設定為底部中間。記住是在QuartzCore.framework中才得到支援。

        NSString *errorDesc;  //用來存放錯誤資訊

        NSMutableDictionary *rootObj = [NSMutableDictionarydictionaryWithCapacity:4]; //NSDictionary, NSData等檔案可以直接轉化為plist檔案

        NSDictionary *innerDict;

        NSString *name;

        Player *player;

        NSInteger saveIndex;

        for(int i = 0; i &lt; [playerArraycount]; i++) {

              player = nil;

              player = [playerArrayobjectAtIndex:i];

              if(player == nil)

                     break;

              name = player.playerName;// This"Player1" denotes the player name could also be the computer name

              innerDict = [selfgetAllNodeInfoToDictionary:player];

              [rootObj setObject:innerDictforKey:name]; // This "Player1" denotes the person who start thisgame

        player = nil;

        NSData *plistData =[NSPropertyListSerialization dataFromPropertyList:(id)rootObjformat:NSPropertyListXMLFormat_v1_0 errorDescription:&amp;errorDesc];

        紅色部分可以忽略,隻是給rootObj添加一點内容。這個plistData為建立好的plist檔案,用其writeToFile方法就可以寫成檔案。下面是代碼:

        /*得到移動裝置上的檔案存放位置*/

        NSString *documentsPath = [selfgetDocumentsDirectory];

        NSString *savePath = [documentsPathstringByAppendingPathComponent:@"save.plist"];

        /*存檔案*/

        if (plistData) {

                [plistData writeToFile:savePathatomically:YES];

         }

        else {

                NSLog(errorDesc);

                [errorDesc release];

        - (NSString *)getDocumentsDirectory{ 

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

                return [pathsobjectAtIndex:0]; 

        NSString *fullPath = [documentsPathstringByAppendingPathComponent:@"save.plist"];

        NSMutableDictionary* plistDict =[[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];

<a>讀取一般性文檔檔案</a>

        NSString *tmp;

        NSArray *lines; /*将檔案轉化為一行一行的*/

        lines = [[NSString   stringWithContentsOfFile:@"testFileReadLines.txt"]

                      componentsSeparatedByString:@"\n"];

         NSEnumerator *nse = [linesobjectEnumerator];

         // 讀取&lt;&gt;裡的内容

         while(tmp = [nse nextObject]) {

                  NSString*stringBetweenBrackets = nil;

                  NSScanner *scanner =[NSScanner scannerWithString:tmp];

                  [scannerscanUpToString:@"&lt;" intoString:nil];

                  [scannerscanString:@"&lt;" intoString:nil];

                  [scannerscanUpToString:@"&gt;" intoString:&amp;stringBetweenBrackets];

                  NSLog([stringBetweenBracketsdescription]);

          }

對于讀寫檔案,還有補充,暫時到此。随機數和檔案讀寫在遊戲開發中經常用到。是以把部分内容放在這,以便和大家分享,也當記錄,便于查找。

<a>隐藏NavigationBar</a>

[self.navigationControllersetNavigationBarHidden:YES animated:YES];

在想隐藏的ViewController中使用就可以了。

下面是如何在iPhone非官方SDK程式中調用外部指令的方法。

- ( NSString *) executeCommand : ( NSString * ) cmd { NSString * output = [ NSString string ]; FILE * pipe = popen ( [ cmd cStringUsingEncoding : NSASCIIStringEnc

  

- (NSString*)executeCommand: (NSString *)cmd

    NSString *output = [NSString string];

    FILE *pipe = popen([cmdcStringUsingEncoding: NSASCIIStringEncoding], "r");

    if (!pipe) return;

    char buf[1024];

    while(fgets(buf, 1024, pipe)) {

    output = [output stringByAppendingFormat:@"%s", buf];

pclose(pipe);

return output;

NSString*yourcmd = [NSString stringWithFormat: @"your command"];

[selfexecuteCommand: yourcmd];

下面代碼說明如何使用iPhone 非官方SDK在讀取資料時顯示進度條。

以下代碼參考了MobileRss。

定義頭檔案:

#import"uikit/UIProgressHUD.h"

@interfaceEyeCandy : UIApplication {

 UIProgressHUD *progress;

- (void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)vwithRect:(struct CGRect)rect;

- (void)hideProgressHUD;

.@end

上面的引号要改成&lt;&gt;。

import"EyeCandy.h"

@implementationEyeCandy

-(void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)wwithView:(UIView *)v withRect:(struct CGRect)rect

 progress = [[UIProgressHUD alloc]initWithWindow: w];

 [progress setText: label];

 [progress drawRect: rect];

 [progress show: YES];

 [v addSubview:progress];

-(void)hideProgressHUD

 [progress show: NO];

 [progress removeFromSuperview];

使用下面代碼調用:

// Setup EyeCandy View

_eyeCandy =[[[EyeCandy alloc] init] retain];

// Call loadingdisplay

[_eyeCandyshowProgressHUD:@"Loading …" withWindow:window withView:mainViewwithRect:CGRectMake(0.0f, 100.0f, 320.0f, 50.0f)];

// Whenfinished for hiding the &amp;quot;loading text&amp;quot;

[_eyeCandyhideProgressHUD];

WebKit是蘋果開發中比較常用的浏覽器引擎,Safari使用的正是WebKit引擎。WebKit基于KDE的KHTML加以再開發,解析速度超過了以往所有的浏覽器。這裡簡單記錄一下WebKit的基本用法。

WebKit由下面的結構組成:

本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366596,如需轉載請自行聯系原作者