1、iphone 开发笔记退回输入键盘- (BOOL) textFieldShouldReturn:(id)textFieldtextField resignFirstResponder;CGRectCGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形NSStringFromCGRect(someCG) 把 CGRect 结构转变为格式化字符串;CGRectFromString(aString) 由字符串恢复出矩形;CGRectInset(aRect) 创建较小或较大的矩形(中心点相同) ,较小 较大C
2、GRectIntersectsRect(rect1, rect2) 判断两矩形是否交叉,是否重叠CGRectZero 高度和宽度为零的位于(0,0)的矩形常量CGPoint CGSize aSize = CGSizeMake(width, height);设置透明度myView setAlpha:value; (0.0 - (IBActive) someButtonPressed:(id) senderUIActionSheet *actionSheet = UIActionSheet alloc initWithTitle:”Are you sure?”delegate:selfcancel
3、ButtonTitle:”No way!”destructiveButtonTitle:”Yes, Im Sure!”otherButtonTitles:nil;actionSheet showInView:self.view;actionSheet release;警告视图 - (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndexif(buttonIndex != actionSheet cancelButtonIndex)NSString *mess
4、age = NSString alloc initWithFormat:”You can breathe easy, everything went OK.”;UIAlertView *alert = UIAlertView alloc initWithTitle:”Something was done”message:messagedelegate:selfcancelButtonTitle:”OK”otherButtonTitles:nil;alert show;alert release;message release;动画效果-(void)doChange:(id)senderif(v
5、iew2 = nil)self loadSec;UIView beginAnimations:nil context:NULL;UIView setAnimationDuration:1; UIView setAnimationTransition:(view1 superview?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.view cache:YES;if(view1 superview!= nil)view1 removeFromSuperview;se
6、lf.view addSubview:view2;else view2 removeFromSuperview;self.view addSubview:view1;UIView commitAnimations;Table View #pragma mark -#pragma mark Table View Data Source Methods/指定分区中的行数,默认为 1- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionreturn self.listData c
7、ount;/设置每一行 cell 显示的内容- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathstatic NSString *SimpleTableIndentifier = “SimpleTableIndentifier“;UITableViewCell *cell = tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier;if (cell = nil) ce
8、ll = UITableViewCell alloc initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIndentifier autorelease;UIImage *image = UIImage imageNamed:“13.gif“;cell.imageView.image = image;NSUInteger row = indexPath row;cell.textLabel.text = listData objectAtIndex:row;cell.textLabel.font = UIF
9、ont boldSystemFontOfSize:20;if(row #pragma mark -#pragma mark Table View Delegate Methods/把每一行缩进级别设置为其行号- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPathNSUInteger row = indexPath row;return row;/获取传递过来的 indexPath 值- (NSIndexPath *)tableView:(
10、UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPathNSUInteger row = indexPath row;if (row = 0) return nil;return indexPath;- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPathNSUInteger row = indexPath row;NSString *rowValue = listData obj
11、ectAtIndex:row;NSString *message = NSString alloc initWithFormat:“You selected %“,rowValue;UIAlertView *alert = UIAlertView alloc initWithTitle:“Row Selected“message:messagedelegate:nilcancelButtonTitle:“Yes, I did!“otherButtonTitles:nil;alert show;alert release;message release;tableView deselectRow
12、AtIndexPath:indexPath animated:YES;/设置行的高度- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPathreturn 40;NavigationController 推出 push 推出 popself.navigationController pushViewController:_detailController animated:YES;self.navigationController popViewController
13、Animated: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:self action:selector(keyboardReturn) forContr
14、olEvents:UIControlEventTouchUpInside;self.view addSubview:m_control;- (void) keyboardReturnaTextField resignFirstResponder;键盘覆盖输入框当键盘调出时将输入框覆盖时,可以用下方法:- (BOOL)textFieldShouldBeginEditing:(UITextField *)textFieldself.view setFrame:CGRectMake(0, -100, 320, 480) ;return YES;- (BOOL)textFieldShouldEndEd
15、iting:(UITextField *)textFieldself.view setFrame:CGRectMake(0, 0, 320, 480);return YES;当准备输入时,将视图的位置上调 100,这样键盘就不能覆盖到输入框。当依赖注入方法不好使时,可以在 AppDelegate 内申明一个全局的控制器实例_anotherViewController,在另一个需要使用_anotherViewController 的地方定义以下委托方法,使用共享的 UIApplication 实例来获取该委托的引用SomeAppDelegate *appDelegate = (SomeAppDe
16、legate *)UIApplication sharedApplication delegate;_anotherViewController = appDelegate._anotherViewController; UIViewController 内建 Table View纯代码在 UIViewController 控制器内建 Table Viewinterface RootViewController : UIViewController NSArray *timeZoneNames;property (nonatomic,retain) NSArray *timeZoneNames
17、;end(void) loadViewUITableView *tableView = UITableView alloc initWithFrame:UIScreen mainScreen applicationFrame style: UITableViewStylePlain;tableView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth);tableView.delegate = self;tableView.dataSource = self;tableView relo
18、adData;self.view = tableView;tableView release;将 plist 文件中的数据赋给数组NSString *thePath = NSBundle mainBundle pathForResource:“States“ ofType:“plist“;NSArray *array = NSArray arrayWithContentsOfFile:thePath;UITouch手指的触摸范围:64X64 #pragma mark -#pragma mark Touch Events- (void)touchesBegan:(NSSet *) touches
19、 withEvent:(UIEvent *) event originFrame = bookCover.frame;NSLog(“%s %d“, _FUNCTION_,_LINE_);if (touches count = 2) NSArray *twoTouches = touches allObjects;UITouch *firstTouch = twoTouches objectAtIndex:0;UITouch *secondTouch = twoTouches objectAtIndex:1;CGPoint firstPoint = firstTouch locationInVi
20、ew:bookCover;CGPoint secondPoint = secondTouch locationInView: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
21、= bookCover.frame.size.width;frameH = bookCover.frame.size.height;NSLog(“%s %d“, _FUNCTION_,_LINE_);- (void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event if(touches count = 2) NSLog(“%s %d“, _FUNCTION_,_LINE_);NSArray *twoTouches = touches allObjects;UITouch *firstTouch = twoTouches obj
22、ectAtIndex:0;UITouch *secondTouch = twoTouches objectAtIndex:1;CGPoint firstPoint = firstTouch locationInView:bookCover;CGPoint secondPoint = secondTouch locationInView:bookCover;CGFloat deltaX = secondPoint.x - firstPoint.x;CGFloat deltaY = secondPoint.y - firstPoint.y; CGFloat currentDistance = sq
23、rt(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 - changedDista
24、nce / 2, frameY - (changedDistance * frameH) / (2 * frameW),frameW + changedDistance, frameH + (changedDistance * frameH) / frameW);- (void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event UITouch *touch = touches anyObject;UITouch 双击图片变大/还原if (touch tapCount = 2) NSLog(“%s %d“, _FUNCTION_
25、,_LINE_);if (!flag) bookCover setFrame: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 bookCover setFrame:CGRectMake(bookCover.frame.origin
26、.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; Get the Location of Touches(CGPoint)locationInView:(UIView *)view(CGPoint)previousLocationInView:(UIView *)viewview windowGetti
27、ng Touch AttributestapCount(read only) timestamp(read only) phase(read only)Getting a Touch Objects Gesture RecognizersgestureRecognizers Touch PhaseUITouchPhaseBeganUITouchPhaseMovedUITouchPhaseStationaryUITouchPhaseEndedUITouchPhaseCancelled从 Plist 里读内容NSString *plistPath = NSBundle mainBundle pat
28、hForResource:“book“ ofType:“plist“;NSDictionary *dictionary = NSDictionary alloc initWithContentsOfFile:plistPath;NSString *book = dictionary objectForKey:bookTitle;textView setText:book;(void) initialize NSUserDefaults = NSUserDefaults standardUserDefaults;NSDictionary *appDefaults = NSDictionary d
29、ictionaryWithObject:“YES“ forKey:“DeleteBackup“;defaults registerDefaults:appDefaults;To get a value of a default, use the valueForKey: method:theDefaultsController values valueForKey:“userName“;To set a value for a default, use setValue:forKey:theDefaultsController values setValue:newUserName forKe
30、y:“userName“;NSUserDefaults standardUserDefaults setValue:aVale forKey:aKey;NSUserDefaults standardUserDefaults valueForKey:aKey;获取 Documents 目录NSArray *paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = paths objectAtIndex:0;NSStr
31、ing *filename = documentsDirectory stringByAppendingPathComponent:“theFile.txt“;获取 tmp 目录NSString *tempPath = NSTemporaryDirectory();NSString *tempFile = tempPath stringByAppendingPathComponent:“tempFile.txt“;NSUserDefaults standardUserDefaults setObject:data forKey:“someKey“;NSUserDefaults standard
32、UserDefaults objectForKey:aKey;自定义 NavigationBarnavigationBar = UINavigationBar alloc initWithFrame:CGRectMake(0, 0, 320, 44);navigationBar setBarStyle:UIBarStyleBlackOpaque;myNavigationItem = UINavigationItem alloc initWithTitle:“Setting“;navigationBar setItems:NSArray arrayWithObject:myNavigationI
33、tem;self.view addSubview:navigationBar;backButton = UIBarButtonItem alloc initWithTitle:“Back“ style:UIBarButtonItemStylePlain target:self action:selector(back);myNavigationItem.leftBarButtonItem = backButton;利用 Safari 打开一个链接NSURL *url = NSURL URLWithString:“http:/ sharedApplication openURL:url;利用 U
34、IWebView 显示 pdf 文件、网页。 。 。webView = UIWebView alloc initWithFrame:CGRectMake(0, 0, 320, 480);webView setDelegate:self;webView setScalesPageToFit:YES;webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;webView setAllowsInlineMediaPlayback:YES;self.view addSu
35、bview:webView;NSString *pdfPath = NSBundle mainBundle pathForResource:“ojc“ ofType:“pdf“; NSURL *url = NSURL fileURLWithPath:pdfPath; NSURLRequest *request = NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:5;webView loadRequest:request;myWebView loadRequ
36、est:NSURLRequest requestWithURL:NSURL URLWithString: “http:/ *errorString = NSString stringWithFormat:“An Error Occurred:%“,error;myWebView loadHTMLString:errorString baseURL:nil;/Stopping a load request when the view is to disappear- (void)viewWillDisappear:(BOOL)animateif (myWebView loading)myWebV
37、iew stopLoading;myWebView.delegate = nil;UIApplication shareAworkActivityIndicatorVisible = NO;汉字转码NSString *oriString = “u67aau738b“;NSString *escapedString = oriString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding;Checking for background support on earlier versions of iOSUIDev
38、ice *device = UIDevice currentDevice;BOOL backgroundSupported = NO;if (device respondsToSelector:selector(isMultitaskingSupported)backgroundSupported = device.multitaskingSupported;Being a Responsible,Multitasking-Aware Application # Do not make any OpenGL ES calls from your code.# Cancel any Bonjou
39、r-related services before being suspended.# Be prepared to handle connection failures in your network-based sockets.# Save your application state before moving to the background.# Release any unneeded memory when moving to the background.# Stop using shared system resources before being suspended.#
40、Avoid updating your windows and views.# Respond to connect and disconnect notification for external accessories.# Clean up resource for active alerts when moving to the background.# Remove sensitive information from views before moving to the background.# Do minimal work while running in the backgro
41、und.Handing the Keyboard notifications/Call this method somewhere in your view controller setup code- (void) registerForKeyboardNotificationsNSNotificationCenter defaultCenter addObserver:selfselector:selector(keyboardWasShown:)name:UIKeyboardDidShowNotification object:nil;NSNotificationCenter defau
42、ltCenter addObserver:selfselector:selector(keyboardWasHidden:)name:UIKeyboardDidHideNotificationobject:nil;/Called when the UIKeyboardDidShowNotification is sent- (void)keyboardWasShown:(NSNotification *) aNotificationif(keyboardShown)return;NSDictionary *info = aNotification userInfo;/get the size
43、of the keyboard. NSValue *aValue = info objectForKey:UIKeyboardFrameBeginUserInfoKey;CGSize keyboardSize = aValue CGRectValue.size;/Resize the scroll view CGRect viewFrame = scrollView frame;viewFrame.size.height -= keyboardSize.height;/Scroll the active text field into viewCGRect textFieldRect = ac
44、tiveField frame;scrollView scrollRectToVisible:textFieldRect animated:YES;keyboardShown = YES; /Called when the UIKeyboardDidHideNotification is sent- (void)keyboardWasHidden:(NSNotification *) aNotificationNSDictionary *info = aNotification userInfo;/Get the size of the keyboard.NSValue *aValue = i
45、nfo objectForKey:UIKeyboardFrameEndUserInfoKey;CGSize keyboardSize = aValue CGRectValue.size;/Reset the height of the scroll view to its original valueCGRect viewFrame = scrollView Frame;viewFrame.size.height += keyboardSize.height;scrollView.frame = viewFrame;keyboardShown = NO;点击键盘的 next 按钮,在不同的 t
46、extField 之间换行/首先给不同的 textField 赋不同的且相邻的 tag 值- (BOOL)textFieldShouldReturn:(UITextField *)textFieldif (textField returnKeyType != UIReturnKeyDone) NSInteger nextTag = textField tag + 1;UIView *nextTextField = self tableView viewWithTag:nextTag;nextTextField becomeFirstResponder;else textField resign
47、FirstResponder;return YES; Configuring a date formatter - (void)viewDidLoad super viewDidLoad;dateFormatter = NSDateFormatter alloc init;dateFormatter setGeneratesCalendarDates:YES;dateFormatter setLocale:NSLocale currentLocale;dateFormatter setCalendar:NSCalendar autoupdatingCurrentCalendar;dateFormatter setTimeZone:NSTimeZone defaultTimeZone;dateFormatter setDateStyle:NSDateFormatterShortStyle;DOB.placeholder = NSString stringWithFormat:“Example: %“,dateFormatter stringFromDate:NSDate date;- (void)textFieldDidEndEditing:(UITextField *)textFieldtextField