之前总结的今天给大分享一下iOS
1 退回输入键盘 2 苹果 ios 开发一年的工作笔记 3 - (BOOL) textFieldShouldReturn:(id)textField{ [textField resignFirstResponder]; 4 } 5 CGRect 6 CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形 NSStringFromCGRect(someCG) 把 CGRect 结构转变为格式化字符串; CGRectFromString(aString) 由字符串恢复出矩形; 7 CGRectInset(aRect) 创建较小或较大的矩形(中心点相同),+较小 -较大 CGRectIntersectsRect(rect1, rect2) 判断两矩形是否交叉,是否重叠 CGRectZero 高度和宽度为零的/位于(0,0)的矩形常量 8 CGPoint & CGSize 9 CGPoint aPoint = CGPointMake(x, y); CGSize aSize = CGSizeMake(width, height); 10 设置透明度 11 [myView setAlpha:value]; (0.0 < value < 1.0) 12 设置背景色 13 [myView setBackgroundColor:[UIColor redColor]]; 14 (blackColor;darkGrayColor;lightGrayColor; whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor; magentaColor;orangeColor;purpleColor; brownColor; clearColor; ) 15 自定义颜色 16 UIColor *newColor = [[UIColor alloc] 17 initWithRed:(float) green:(float) blue:(float) alpha:(float)]; 18 0.0~1.0 19 竖屏 20 320X480 21 横屏 22 480X320 23 状态栏高 (显示时间和网络状态) 20 像素 24 导航栏、工具栏高(返回) 44 像素 25 隐藏状态栏 26 [[UIApplication shareApplication] setStatusBarHidden: YES animated:NO] 27 横屏 28 [[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight]. 29 屏幕变动检测 30 orientation == UIInterfaceOrientationLandscapeLeft 31 全屏 32 window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds]; 33 自动适应父视图大小: 34 aView.autoresizingSubviews = YES; 35 aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | 36 UIViewAutoresizingFlexibleHeight); 37 定义按钮 38 UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal]; scaleUpButton.frame = CGRectMake(40, 420, 100, 40); 39 [scaleUpButton addTarget:self 40 action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside]; 41 设置视图背景图片 42 UIImageView *aView; 43 [aView setImage:[UIImage imageNamed:@”name.png”]]; view1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"image1.png"]]; 44 自定义 UISlider 的样式和滑块 45 46 我们使用的是 UISlider 的 setMinimumTrackImage,和 setMaximumTrackImage 方法来定义图 片的,这两个方法可以设置滑块左边和右边的图片的,不过如果用的是同一张图片且宽度和 控件宽度基本一致,就不会有变形拉伸的后果,先看代码,写在 viewDidLoad 中: 47 //左右轨的图片 48 UIImage *stetchLeftTrack= [UIImage imageNamed:@"brightness_bar.png"]; UIImage *stetchRightTrack = [UIImage imageNamed:@"brightness_bar.png"]; //滑块图片 49 UIImage *thumbImage = [UIImage imageNamed:@"mark.png"]; 50 UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320, 257, 7)]; sliderA.backgroundColor = [UIColor clearColor]; 51 sliderA.value=1.0; 52 sliderA.minimumValue=0.7; 53 sliderA.maximumValue=1.0; 54 [sliderA setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal]; 55 [sliderA setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal]; //注意这里要加UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的 56 控件 57 [sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted]; [sliderA setThumbImage:thumbImage forState:UIControlStateNormal]; //滑块拖动时的事件 58 [sliderA addTarget:self action:@selector(sliderValueChanged:) 59 forControlEvents:UIControlEventValueChanged]; //滑动拖动后的事件 60 [sliderA addTarget:self action:@selector(sliderDragUp:) 61 forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:sliderA]; 62 为了大家实验方便,我附上背景图brightness_bar.png和滑块图mark.png http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png 63 -(IBAction)sliderValueChanged:(id)sender{ 64 UISlider *slider = (UISlider *) sender; 65 NSString *newText = [[NSString alloc] initWithFormat:@”%d”, (int)(slider.value + 0.5f)]; label.text = newText; 66 } 67 活动表单 68  69 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 70 <UIActionSheetDelegate> 71 - (IBActive) someButtonPressed:(id) sender { 72 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@”Are you sure?” 73 delegate:self 74 cancelButtonTitle:@”No way!” destructiveButtonTitle:@”Yes, I’m Sure!” otherButtonTitles:nil]; 75 [actionSheet showInView:self.view]; 76 [actionSheet release]; } 77 警告视图 78 <UIAlertViewDelegate> 79 - (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex 80 { 81 if(buttonIndex != [actionSheet cancelButtonIndex]) { 82 NSString *message = [[NSString alloc] initWithFormat:@”You can breathe easy, everything went OK.”]; 83 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Something was done” 84 [alert show]; [alert release]; [message release]; 85 } } 86 动画效果 87 -(void)doChange:(id)sender { 88 if(view2 == nil) 89 { 90 [self loadSec]; 91 message:message delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil]; 93 } 94 [UIView beginAnimations:nil context:NULL]; 95 [UIView setAnimationDuration:1]; 96 [UIView setAnimationTransition:([view1 superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRigh t)forView:self.view cache:YES]; 97 if([view1 superview]!= nil) { 98 [view1 removeFromSuperview]; [self.view addSubview:view2]; 99 }else { 100 [view2 removeFromSuperview]; [self.view addSubview:view1]; } 101 [UIView commitAnimations]; 102 } 103 Table View <UITableViewDateSource> #pragma mark - 104 #pragma mark Table View Data Source Methods //指定分区中的行数,默认为 1 105 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 106 { 107 return [self.listData count]; } 108 //设置每一行 cell 显示的内容 109 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 110 { 111 static NSString *SimpleTableIndentifier = @"SimpleTableIndentifier"; 112 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier]; if (cell == nil) { 113 cell = [[[UITableViewCell alloc] 114 initWithStyle:UITableViewCellStyleSubtitle 115 reuseIdentifier:SimpleTableIndentifier] 116 autorelease]; 117 } 118 UIImage *image = [UIImage imageNamed:@"13.gif"]; cell.imageView.image = image; 119 NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; 120 cell.textLabel.font = [UIFont boldSystemFontOfSize:20]; 121 if(row < 5) 122 cell.detailTextLabel.text = @"Best friends"; else 123 cell.detailTextLabel.text = @"friends"; return cell; 124 } 125 图像、文本标签和详细文本标签 126 图像:如果设置图像,则它显示在文本的左侧; 文本标签:这是单元的主要文本 (UITableViewCellStyleDefault 只显示文本标签);详细文本标签:这是单元的辅助文本, 通常用作解释性说明或标签 127 UITableViewCellStyleSubtitle UITableViewCellStyleDefault UITableViewCellStyleValue1 UITableViewCellStyleValue2 128 <UITableViewDelegate> 129 #pragma mark - 130 #pragma mark Table View Delegate Methods //把每一行缩进级别设置为其行号 131 - (NSInteger)tableView:(UITableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath { 132 NSUInteger row = [indexPath row]; 133 return row; 134 } 135 //获取传递过来的 indexPath 值 136 - (NSIndexPath willSelectRowAtIndexPath:(NSIndexPath *)indexPath 137 { 138 NSUInteger row = [indexPath row]; 139 if (row == 0) 140 return nil; 141 *)tableView 142 *)tableView 143 *)tableView:(UITableView 144 return indexPath; } 145 - (void)tableView:(UITableView 146 *)indexPath 147 { 148 NSUInteger row = [indexPath row]; 149 NSString *rowValue = [listData objectAtIndex:row]; 150 NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",rowValue]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Row Selected" message:message 151 delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil]; 152 [alert show]; 153 [alert release]; 154 [message release]; 155 [tableView deselectRowAtIndexPath:indexPath animated:YES]; } 156 //设置行的高度 157 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 158 { 159 return 40; 160 } 161 NavigationController 推出 push 推出 pop 162 [self.navigationController pushViewController:_detailController animated:YES]; [self.navigationController popViewControllerAnimated:YES]; 163 Debug: 164 NSLog(@"%s %d", __FUNCTION__, __LINE__); 165 点击 textField 外的地方回收键盘 166 先定义一个 UIControl 类型的对象,在上面可以添加触发事件,令 SEL 实践为回收键盘的方 法,最后将 UIControl 的实例加到当前 View 上。 167 UIControl *m_control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [m_control addTarget:self action:@selector(keyboardReturn) forControlEvents:UIControlEventTouchUpInside]; 168 [self.view addSubview:m_control]; 169 *)tableView 170 didSelectRowAtIndexPath:(NSIndexPath 171 - (void) keyboardReturn 172 { 173 [aTextField resignFirstResponder]; } 174 键盘覆盖输入框 175 当键盘调出时将输入框覆盖时,可以用下方法: 176 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 177 [self.view setFrame:CGRectMake(0, -100, 320, 480) ]; 178 return YES; 179 } 180 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 181 [self.view setFrame:CGRectMake(0, 0, 320, 480)]; return YES; 182 } 183 当准备输入时,将视图的位置上调 100,这样键盘就不能覆盖到输入框。 184 当依赖注入方法不好使时,可以在 AppDelegate 内申明一个全局的控制器实例 _anotherViewController,在另一个需要使用_anotherViewController 的地方定义以下委托方 法,使用共享的 UIApplication 实例来获取该委托的引用 185 SomeAppDelegate *appDelegate = (SomeAppDelegate *)[[UIApplication sharedApplication] delegate]; 186 _anotherViewController = appDelegate._anotherViewController; 187 UIViewController 内建 Table View 188 纯代码在 UIViewController 控制器内建 Table View 189 @interface RootViewController : UIViewController UITableViewDataSource> { 190 NSArray *timeZoneNames; 191 } 192 @property (nonatomic,retain) NSArray *timeZoneNames; 193 @end 194 <UITableViewDelegate, 195 (void) loadView 196 { 197 UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] style: UITableViewStylePlain]; 198 tableView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth); 200 tableView.delegate = self; tableView.dataSource = self; [tableView reloadData]; 201 self.view = tableView; [tableView release]; 202 } 203 将 plist 文件中的数据赋给数组 204 NSString *thePath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"]; NSArray *array = [NSArray arrayWithContentsOfFile:thePath]; 205 UITouch 手指的触摸范围:64X64 206 #pragma mark - 207 #pragma mark Touch Events 208 - (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event { originFrame = bookCover.frame; 209 NSLog(@"%s %d", __FUNCTION__,__LINE__); 210 if ([touches count] == 2) 211 { 212 NSArray *twoTouches = [touches allObjects]; 213 UITouch *firstTouch = [twoTouches objectAtIndex:0]; 214 UITouch *secondTouch = [twoTouches objectAtIndex:1]; 215 CGPoint firstPoint = [firstTouch locationInView:bookCover]; CGPoint secondPoint = [secondTouch locationInView:bookCover]; 216 CGFloat deltaX = secondPoint.x - firstPoint.x; 217 CGFloat deltaY = secondPoint.y - firstPoint.y; initialDistance = sqrt(deltaX * deltaX + deltaY * deltaY ); frameX = bookCover.frame.origin.x; 218 frameY = bookCover.frame.origin.y; 219 frameW = bookCover.frame.size.width; 220 frameH = bookCover.frame.size.height; 221 NSLog(@"%s %d", __FUNCTION__,__LINE__); 222 } 223 } 224 - (void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event { 225 if([touches count] == 2) 226 { 227 NSLog(@"%s %d", __FUNCTION__,__LINE__); 228 NSArray *twoTouches = [touches allObjects]; 229 UITouch *firstTouch = [twoTouches objectAtIndex:0]; UITouch *secondTouch = [twoTouches objectAtIndex:1]; 230 CGPoint firstPoint = [firstTouch locationInView:bookCover]; CGPoint secondPoint = [secondTouch locationInView:bookCover]; 231 CGFloat deltaX = secondPoint.x - firstPoint.x; 232 CGFloat deltaY = secondPoint.y - firstPoint.y; 233 CGFloat currentDistance = sqrt(deltaX * deltaX + deltaY * deltaY ); 234 if (initialDistance == 0) { 235 initialDistance = currentDistance; 236 } 237 else if (currentDistance != initialDistance) 238 { 239 CGFloat changedDistance = currentDistance - initialDistance; NSLog(@"changedDistance = %f",changedDistance); 240 [bookCover setFrame:CGRectMake(frameX - changedDistance / 2, frameY - (changedDistance * frameH) / (2 * frameW), 241 frameW + changedDistance, 242 frameH + (changedDistance * frameH) / frameW)]; 243 } 244 } 245 } 246 - (void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event { UITouch *touch = [touches anyObject]; 247 UITouch 双击图片变大/还原 248 if ([touch tapCount] == 2) 249 { 250 NSLog(@"%s %d", __FUNCTION__,__LINE__); 251 if (!flag) { 252 [bookCover setFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2, 253 bookCover.frame.origin.y - bookCover.frame.size.height / 2, 2 * bookCover.frame.size.width, 254 2 * bookCover.frame.size.height)]; 255 flag = YES; 256 } 257 else { 258 [bookCover setFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4, bookCover.frame.origin.y + bookCover.frame.size.height / 4, 259 bookCover.frame.size.width / 2, bookCover.frame.size.height / 2)]; 260 flag = NO; 261 } 262 } 263 } 264 Get the Location of Touches 265 (CGPoint)locationInView:(UIView *)view (CGPoint)previousLocationInView:(UIView *)view view window 266 Getting Touch Attributes 267 tapCount(read only) timestamp(read only) phase(read only) 268 Getting a Touch Object\'s Gesture Recognizers gestureRecognizers 269 Touch Phase 270 UITouchPhaseBegan UITouchPhaseMoved UITouchPhaseStationary UITouchPhaseEnded UITouchPhaseCancelled 271 从 Plist 里读内容 272 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"]; NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; NSString *book = [dictionary objectForKey:bookTitle]; 273 [textView setText:book]; 274 (void) initialize { 275 NSUserDefaults = [NSUserDefaults standardUserDefaults]; 276 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"YES" forKey:@"DeleteBackup"]; 277 [defaults registerDefaults:appDefaults]; } 278 To get a value of a default, use the valueForKey: method: [[theDefaultsController values] valueForKey:@"userName"]; 279 To set a value for a default, use setValue:forKey: 280 [[theDefaultsController values] setValue:newUserName forKey:@"userName"]; 281 [[NSUserDefaults standardUserDefaults] setValue:aVale forKey:aKey]; [[NSUserDefaults standardUserDefaults] valueForKey:aKey]; 282 获取 Documents 目录 283 NSArray *paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 284 NSString *documentsDirectory = [paths objectAtIndex:0]; 285 NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"theFile.txt"]; 286 获取 tmp 目录 287 NSString *tempPath = NSTemporaryDirectory(); 288 NSString *tempFile = [tempPath stringByAppendingPathComponent:@"tempFile.txt"]; 289 [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"someKey"]; [[NSUserDefaults standardUserDefaults] objectForKey:aKey]; 290 自定义 NavigationBar 291 navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; [navigationBar setBarStyle:UIBarStyleBlackOpaque]; 292 myNavigationItem = [[UINavigationItem alloc] initWithTitle:@"Setting"]; [navigationBar setItems:[NSArray arrayWithObject:myNavigationItem]]; [self.view addSubview:navigationBar]; 293 backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)]; 294 myNavigationItem.leftBarButtonItem = backButton; 295 利用 Safari 打开一个链接 296 NSURL *url = [NSURL URLWithString:@"http://www.cnblogs.com/tracy-e/"]; [[UIApplication sharedApplication] openURL:url]; 297 利用 UIWebView 显示 pdf 文件、网页。。。 298 webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 299 [webView setDelegate:self]; 300 [webView setScalesPageToFit:YES]; 301 [webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; 302 [webView setAllowsInlineMediaPlayback:YES]; 303 [self.view addSubview:webView]; 304 NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"ojc" ofType:@"pdf"]; NSURL *url = [NSURL fileURLWithPath:pdfPath]; 305 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy 306 timeoutInterval:5]; 307 [webView loadRequest:request]; 308 [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: @"http://www.cnblogs.com/tracy-e/"]]]; 309 NSString *errorString = [NSString stringWithFormat:@"<html><center><font size= +5 color =\'red\'>An Error Occurred:<br>%@</fone></center></html>",error]; [myWebView loadHTMLString:errorString baseURL:nil]; 310 //Stopping a load request when the view is to disappear - (void)viewWillDisappear:(BOOL)animate{ 311 if ([myWebView loading]){ 312 [myWebView stopLoading]; 313 } 314 myWebView.delegate = nil; 315 [UIApplication shareApplication].networkActivityIndicatorVisible = NO; } 316 汉字转码 317 NSString *oriString = @"\u67aa\u738b"; 318 NSString *escapedString = [oriString stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; 319 Checking for background support on earlier versions of iOS 320 UIDevice *device = [UIDevice currentDevice]; 321 BOOL backgroundSupported = NO; 322 if ([device respondsToSelector:@selector(isMultitaskingSupported)]){ 323 backgroundSupported = device.multitaskingSupported; } 324 Being a Responsible,Multitasking-Aware Application 325 # Do not make any OpenGL ES calls from your code. 326 # Cancel any Bonjour-related services before being suspended. 327 # Be prepared to handle connection failures in your network-based sockets. 328 # Save your application state before moving to the background. 329 # Release any unneeded memory when moving to the background. 330 # Stop using shared system resources before being suspended. 331 # Avoid updating your windows and views. 332 # Respond to connect and disconnect notification for external accessories. 333 # Clean up resource for active alerts when moving to the background. 334 # Remove sensitive information from views before moving to the background. # Do minimal work while running in the background. 335 Handing the Keyboard notifications 336 //Call this method somewhere in your view controller setup code - (void) registerForKeyboardNotifications{ 337 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification 338 object:nil]; 339 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification 340 object:nil]; 341 } 342 //Called when the UIKeyboardDidShowNotification is sent 343 - (void)keyboardWasShown:(NSNotification *) aNotification{ if(keyboardShown) 344 return; 345 NSDictionary *info = [aNotification userInfo]; 346 //get the size of the keyboard. 347 NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue].size; 348 //Resize the scroll view 349 CGRect viewFrame = [scrollView frame]; viewFrame.size.height -= keyboardSize.height; 350 //Scroll the active text field into view 351 CGRect textFieldRect = [activeField frame]; 352 [scrollView scrollRectToVisible:textFieldRect animated:YES]; 353 keyboardShown = YES; } 354 //Called when the UIKeyboardDidHideNotification is sent 355 - (void)keyboardWasHidden:(NSNotification *) aNotification{ NSDictionary *info = [aNotification userInfo]; 356 //Get the size of the keyboard. 357 NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue].size; 358 //Reset the height of the scroll view to its original value CGRect viewFrame = [scrollView Frame]; viewFrame.size.height += keyboardSize.height; scrollView.frame = viewFrame; 359 keyboardShown = NO; } 360 点击键盘的 next 按钮,在不同的 textField 之间换行 //首先给不同的 textField 赋不同的且相邻的 tag 值 361 - (BOOL)textFieldShouldReturn:(UITextField *)textField 362 { 363 if ([textField returnKeyType] != UIReturnKeyDone) 364 { 365 NSInteger nextTag = [textField tag] + 1; 366 UIView *nextTextField = [[self tableView] viewWithTag:nextTag]; [nextTextField becomeFirstResponder]; 367 } 368 else { 369 [textField resignFirstResponder]; 370 } 371 return YES; 372 } 373 Configuring a date formatter 374 - (void)viewDidLoad { 375 [super viewDidLoad]; 376 dateFormatter = [[NSDateFormatter alloc] init]; 377 [dateFormatter setGeneratesCalendarDates:YES]; 378 [dateFormatter setLocale:[NSLocale currentLocale]]; 379 [dateFormatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]]; 380 [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; 381 [dateFormatter setDateStyle:NSDateFormatterShortStyle]; 382 DOB.placeholder = [NSString stringWithFormat:@"Example: %@",[dateFormatter stringFromDate:[NSDate date]]]; 383 } 384 - (void)textFieldDidEndEditing:(UITextField *)textField{ [textField resignFirstResponder]; 385 if ([textField.text isEqualToString:@""]) 386 return; 387 switch (textField.tag){ 388 case DOBField: 389 NSDate *theDate = [dateFormatter dateFromString:textField.text]; if (theDate) 390 [inputDate setObject:theDate forKey:MyAppPersonDOBKey]; break; 391 default: 392 break; 393 } 394 } 395 tableView 的 cell 高度 396 tableView 的 cell 高度除了在 delegate 中指定外,还可以在任意位置以[tableView 397 setRowHeight:44]的方式指定 398 [[self navigationItem] setLeftBarButtonItem:[self editButtonItem]]; 399 - (void)setEditing:(BOOL)editing animated:(BOOL)animated{ [super setEditing:editing animated:animated]; 400 if (editing){ 401 ...... 402 } else{ ...... 403 } } 404 One added a subview to a view, release the subview to avoid the extra retain count of it, Because when you insert a view as a subview using addSubview:, the subview is retained by its superview. When you remove the subview from its superview using the removeFromSuperview: method, subview is autoreleased. 405 为 UINavigationBar 设置背景图片 406 在 iPhone 开发中, 有时候我们想给导航条添加背景图片, 实现多样化的导航条效果, 用 407 其他方法往往无法达到理想的效果, 经过网上搜索及多次实验, 确定如下最佳实现方案: 408 为 UINavigatonBar 增加如下 Category(类别:提供一种为某个类添加方法而又不必编写子 409 类的途径,类别只能添加成员函数,不能添加数据成员): 410 @implementation UINavigationBar (CustomImage) - (void)drawRect:(CGRect)rect { 411 UIImage *image = [UIImage imageNamed: @"NavigationBar.png"]; 412 [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; } 413 @end 414 例如, 在我的项目中, 添加如下代码: ///////////////////////////////////////////////////////// 415 /* input: The image and a tag to later identify the view */ @implementation UINavigationBar (CustomImage) 416 - (void)drawRect:(CGRect)rect { 417 UIImage *image = [UIImage imageNamed: @"title_bg.png"]; 418 [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; } 419 @end 420 ///////////////////////////////////////////////////////// 421 @implementation FriendsPageViewController 422 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { 423 self.navigationBar.tintColor = [UIColor purpleColor]; 424 [self initWithRootViewController:[[RegPageViewController alloc] init]]; 425 [super viewDidLoad]; } 426 ...... 427 实现的效果如下图: 428 为 UINavigationBar 添加自定义背景 429 @implementation UINavigationBar (UINavigationBarCategory) 430 - (void)drawRect:(CGRect)rect { //颜色填充 431 // UIColor *color = [UIColor redColor]; 432 // CGContextRef context = UIGraphicsGetCurrentContext(); 433 // CGContextSetFillColor(context, CGColorGetComponents( [color CGColor])); 434 // CGContextFillRect(context, rect); 435 // self.tintColor = color; 436 //图片填充 437 UIColor *color = [UIColor colorWithRed:46.0f/255.0f green:87.0f/255.0f blue:29.0f/255.0f alpha:1.0f]; 438 UIImage *img = [UIImage imageNamed: @"bg.png"]; 439 [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 440 self.tintColor = color; } 441 @end 442 加载图片要及时 release 443 你还在使用 myImage = [UIImage imageNamed:@"icon.png"]; 吗? 如题,是不是大家为了方便都这样加载图片啊 444 myImage = [UIImage imageNamed:@"icon.png"]; 445 那么小心了 这种方法在一些图片很少,或者图片很小的程序里是 ok 的。 但是,在大量加载图片的程序里,请千万不要这样做。 为什么呢 ??????? 446 这种方法在 application bundle 的顶层文件夹寻找由供应的名字的图象。 如果找到图片,装 载到 iPhone 系统缓存图象。那意味图片是(理论上)放在内存里作为 cache 的。 447 试想你图片多了,是什么后果? 448 图片 cache 极有可能不会响应 memory warnings and release its objects 449 所以,用图片的时候一定要小心的 alloc 和 release。 450 推 荐 使 用 NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]; 451 myImage = [UIImage imageWithContentsOfFile:path]; 452 // Todo use of myImage 453 [myImage release]; 454 From: http://www.cocoachina.com/bbs/simple/?t27420.html 455 uiwebview 打开 doc,pdf 文件 456 UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 55, 320, 300)]; 457 webView.delegate = self; webView.multipleTouchEnabled = YES; webView.scalesPageToFit = YES; 458 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 459  460 NSUserDomainMask, YES); 461 NSString *documentsDirectory = [paths objectAtIndex:0]; 462 NSString *docPath = [documentsDirectory stringByAppendingString:@"/doc2003_1.doc"]; 463 NSLog(@"#######%@",docPath); 464 NSURL *url = [NSURL fileURLWithPath:docPath]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; 465 [self.view addSubview:webView]; [webView release]; 466 From:http://blog.csdn.net/dadalan/archive/2010/10/22/5959301.aspx 467 iPhone 游戏中既播放背景音乐又播放特效声音的办法 468 有时候在 iPhone 游戏中,既要播放背景音乐,同时又要播放比如枪的开火音效。此时 您可以试试以下方法 469 NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"]; //创建音乐文件路径 470 NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath]; 471 AVAudioPlayer* musicPlayer = [[AVAudioPlayer initWithContentsOfURL:musicURL error:nil]; 472 [musicURL release]; 473 [musicPlayer prepareToPlay]; 474 //[musicPlayer setVolume:1]; //设置音量大小 475 //musicPlayer .numberOfLoops = -1;//设置音乐播放次数 -1 为一直循环 476 要 导 入 框 架 AVFoundation.framework , 头 文 件 中 <AVFoundation/AVFoundation.h>;做成类的话则更方便。 477 From: http://blog.csdn.net/dadalan/archive/2010/10/19/5950493.aspx 478 NSNotificationCenter 用于增加回调函数 479 alloc] 480 #import 481 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_willBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; 482 UINavigationBar 背景 Hack LOGO_320×44.png 图片显示在背景上, 484 @implementation UINavigationBar (UINavigationBarCategory) - (void)drawRect:(CGRect)rect { 485 //加入旋转坐标系代码 // Drawing code 486 UIImage *navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0.0, self.frame.size.height); CGContextScaleCTM(context, 1.0, -1.0); 487 CGPoint center=self.center; 488 CGImageRef cgImage= CGImageCreateWithImageInRect(navBarImage.CGImage, CGRectMake(0, 0, 1, 44)); 489 CGContextDrawImage(context, CGRectMake(center.x-160-80, 0, 80, self.frame.size.height), cgImage); 490 CGContextDrawImage(context, CGRectMake(center.x-160, 0, 320, self.frame.size.height), navBarImage.CGImage); 491 CGContextDrawImage(context, CGRectMake(center.x+160, 0, 80, self.frame.size.height), cgImage); 492 } @end 493 old code 494 CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), navBarImage.CGImage); 495 hack 过 logo 不再拉伸 496 From: http://blog.163.com/fengyi1103@126/blog/static/13835627420106279102671/ 清除电话号码中的其他符号(源码) 497 最近从通讯录读取电话号码,读出得号码如:134-1814-****。 而我需要的为 11 位纯数字,一直找方法解决此问题,今天终于找到了。 501 代码如下: 502 NSString *originalString = @"(123) 123123 abc"; NSMutableString *strippedString = [NSMutableString 503 stringWithCapacity:originalString.length]; 504 NSScanner *scanner = [NSScanner scannerWithString:originalString]; NSCharacterSet *numbers = [NSCharacterSet 505 characterSetWithCharactersInString:@"0123456789"]; 506 while ([scanner isAtEnd] == NO) { 507 NSString *buffer; 508 if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) { 509 [strippedString appendString:buffer]; } 510 // --------- Add the following to get out of endless loop else { 511 [scanner setScanLocation:([scanner scanLocation] + 1)]; } 512 // --------- End of addition } 513 NSLog(@"%@", strippedString); // "123123123" 514 From: http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring 515 正则判断:字符串只包含字母和数字 516 NSString *mystring = @"Letter1234"; NSString *regex = @"[a-z][A-Z][0-9]"; 517 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 518 if ([predicate evaluateWithObject:mystring] == YES) { //implement 519 } 520 一行代码设置 UITableViewCell 与导航条间距
523 UITableView 的 cell 默认出现在 uitableview 的第一行,如果你想自定义 UITableViewCell 与导航条间距的话,可以使用下面这行代码 524 tableview.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)]autorelease]; 525 From: http://blog.163.com/fengyi1103@126/blog/static/1383562742010101611107492/ 526 修改 UITableview 滚动条颜色的方法 527 UITableview 的滚动条默认颜色是黑色的,如果 UItableview 背景也是深颜色,则 528 滚动条会变的很不明显。您可以用下面这行代码来改变滚动条的颜色 529 self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite; 当然,最后的 “White” 也可以换成其它颜色。 530 下文件之前获取到文件大小的代码 531 下面这段代码,能实现在下载文件之前获得文件大小,应用在软件里,能在很大程度 上改善用户体验 532 [m_pASIHTTPRequest setDidReceiveResponseHeadersSelector:@selector(didReceiveResponseHeaders:)]; 533 - (void)didReceiveResponseHeaders:(ASIHTTPRequest *)request { 534 NSLog(@"didReceiveResponseHeaders valueForKey:@"Content-Length"]); 535 } 536 网络编程总结 iphone 一:确认网络环境 3G/WIFI 537 1. 添加源文件和 framework 538 %@",[m_request.responseHeaders 539 开发 Web 等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没 有处理它们,是不会通过 Apple 的审(我们的)查的。 540 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 541 Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。要在应用程序程 序中使用 Reachability,首先要完成如下两部: 542 1.1. 添加源文件: 543 在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图: 544 1.2.添加 framework: 545 将 SystemConfiguration.framework 添加进工程。如下图: 546 2. 网络状态 547 Reachability.h 中定义了三种网络状态: typedef enum { 548 NotReachable = 0, ReachableViaWiFi, ReachableViaWWAN 549 } NetworkStatus; 550 因此可以这样检查网络状态: 551 //无连接 552 //使用 3G/GPRS 网络 553 //使用 WiFi 网络 554 Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”]; switch ([r currentReachabilityStatus]) { 555 } 556 case NotReachable: 557 // 没有网络连接 558 break; 559 case ReachableViaWWAN: 560 // 使用 3G 网络 561 break; 562 case ReachableViaWiFi: 563 // 使用 WiFi 网络 break; 564 3.检查当前网络环境 程序启动时,如果想检测可用的网络环境,可以像这样 // 是否 wifi 565 + (BOOL) IsEnableWIFI { 566 return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != 568 NotReachable); } 569 // 是否 3G 570 + (BOOL) IsEnable3G { 571 return ([[Reachability currentReachabilityStatus] != NotReachable); 572 } 573 例子: 574 - (void)viewWillAppear:(BOOL)animated { 575 reachabilityForInternetConnection] 576 if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) && 577 NotReachable)) { 578 ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == 579 self.navigationItem.hidesBackButton = YES; 580 [self.navigationItem setLeftBarButtonItem:nil animated:NO]; } 581 } 582 4. 链接状态的实时通知 583 网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变 化时,需要及时地通知用户: 584 Reachability 1.5 版本 585 // My.AppDelegate.h #import "Reachability.h" 586 @interface MyAppDelegate : NSObject <UIApplicationDelegate> { NetworkStatus remoteHostStatus; 587 } 588 @property NetworkStatus remoteHostStatus; 589 @end 590 // My.AppDelegate.m #import "MyAppDelegate.h" 591 @implementation MyAppDelegate @synthesize remoteHostStatus; 592 // 更新网络状态 594 - (void)updateStatus { 595 self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; 596 } 597 // 通知网络状态 598 - (void)reachabilityChanged:(NSNotification *)note { 599 [self updateStatus]; 600 if (self.remoteHostStatus == NotReachable) { 601 UIAlertView *alert = initWithTitle:NSLocalizedString(@"AppName", nil) 602 [[UIAlertView 603 alloc] 604 [alert show]; 605 [alert release]; } 606 } 607 message:NSLocalizedString (@"NotReachable", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 608 // 程序启动器,启动网络监视 609 - (void)applicationDidFinishLaunching:(UIApplication *)application { 610 // 设置网络检测的站点 611 [[Reachability sharedReachability] setHostName:@"www.apple.com"]; [[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES]; 612 // 设置网络状态变化时的通知函数 613 [[NSNotificationCenter defaultCenter] addObserver:self 614 selector:@selector(reachabilityChanged:) 615 name:@"kNetworkReachabilityChangedNotification" object:nil]; [self updateStatus]; 616 } 617 - (void)dealloc { 618 // 删除通知对象 619 [[NSNotificationCenter defaultCenter] removeObserver:self]; [window release]; 620 [super dealloc]; 621 } 622 Reachability 2.0 版本 623 // MyAppDelegate.h 624 retain]; 625 // 监测网络情况 626 [[NSNotificationCenter defaultCenter] addObserver:self 627 selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; 628 hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] 629 hostReach startNotifer]; 631 @class Reachability; 632 @interface MyAppDelegate : NSObject <UIApplicationDelegate> { Reachability *hostReach; 633 } @end 634 // MyAppDelegate.m 635 - (void)reachabilityChanged:(NSNotification *)note { 636 Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); NetworkStatus status = [curReach currentReachabilityStatus]; 637 if (status == NotReachable) { 638 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"" 639 } } 640 message:@"NotReachable" 641 delegate:nil 642 cancelButtonTitle:@"YES" otherButtonTitles:nil]; [alert show]; 643 [alert release]; 644 - (void)applicationDidFinishLaunching:(UIApplication *)application { // ... 645 // ... } 646 二:使用 NSConnection 下载数据 647 1.创建 NSConnection 对象,设置委托对象 649 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; 650 [NSURLConnection connectionWithRequest:request delegate:self]; 651 2. NSURLConnection delegate 委托方法 652 - (void)connection:(NSURLConnection *)connection 653 didReceiveResponse:(NSURLResponse *)response; 654 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError 655 *)error; *)data; 656 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 657 // store data 658 [self.receivedData setLength:0]; //通常在这里先清空接受数据的缓 659 存 660 } 661 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { /* appends the new data to the received data */ 662 [self.receivedData appendData:data]; //可能多次收到数据,把新的数据 添加在现有数据最后 663 } 664 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 665 // 错误处理 } 666 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // disconnect 667 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 668 NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; 669 NSLog(returnString); 670 [self urlLoaded:[self urlString] data:self.receivedData]; firstTimeDownloaded = YES; 671 } 672 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData 673 - (void)connectionDidFinishLoading:(NSURLConnection *)connection; 674 3. 实现委托方法 676 三:使用 NSXMLParser 解析 xml 文件 677 1. 设置委托对象,开始解析 678 NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //或者也可以 使用 initWithContentsOfURL 直接下载文件,但是有一个原因不这么做: 679 // It\'s also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable 680 // because it gives less control over the network, particularly in responding to connection errors. 681 [parser setDelegate:self]; [parser parse]; 682 2. 常用的委托方法 683 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 684 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict; 685 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 686 qualifiedName:(NSString *)qName; 687 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; 688 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError; static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml"; 689 3. 应用举例 690 - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error { 691 NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL]; [parser setDelegate:self]; 692 [parser setShouldProcessNamespaces:NO]; 693 [parser setShouldReportNamespacePrefixes:NO]; 694 [parser setShouldResolveExternalEntities:NO]; [parser parse]; 695 NSError *parseError = [parser parserError]; 696 if (parseError && error) { 697 *error = parseError; } 698 [parser release];
701 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 702 attributes:(NSDictionary *)attributeDict{ // 元素开始句柄 703 if (qName) { 704 elementName = qName; 705 } 706 if ([elementName isEqualToString:@"user"]) { 707 // 输出属性值 708 NSLog(@"Name is %@ , Age objectForKey:@"name"], [attributeDict objectForKey:@"age"]); 709 } } 710 is %@", 711 [attributeDict 712 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 713 { 714 // 元素终了句柄 715 if (qName) { 716 elementName = qName; 717 } } 718 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 719 // 取得元素的 text } 720 NSError *parseError = nil; 721 [self parseXMLFileAtURL:[NSURL parseError:&parseError]; 722 Iphone 实现画折线图 723 URLWithString:feedURLString] 724 iphone 里面要画图一般都是通过 CoreGraphics.framwork 和 QuartzCore.framwork 实现,apple 的官方 sdk demon 中包含了 QuartzCore 的基本用法, 725 qualifiedName:(NSString*)qName 726 qualifiedName:(NSString *)qName 727 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 728 具体 demo 请参考 http://developer.apple.com/library/ios/#samplecode/QuartzDemo/ 折线图 729 要实现折线图也就把全部的点连起来,movePointLineto,具体的调用里面的 api 就可以实现 了,但是画坐标就比较麻烦了,里面需要去转很多,好在国外有人开源了一个画折线图的开 发包,首先看看效果吧,具体怎么用可以参考作者 git 版本库中的 wiki。 http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library 730 这个包还提供了其他的很好看的 UI,都可以调来用,但是我们只需要一个画图要把整个包 都导进去,工程太大了,既然是开源的那就想办法提取出来吧,原先之前也有人干过这样的 事。 http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/ 731  732 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 733 我对源代码进行简单的修改,使其显示坐标之类的,更加符合工程的需要,但是还 没有实现画多组数据,只能画一组数据,不用 viewContol,而使用 addsubview,直 接添加到当前的窗口,最终效果如下。 734 使用方法: 735 1.工程添加 tk 库里面的如下文件 736 2. 添加 QuartzCore framework 737 #import <QuartzCore/QuartzCore.h> 738 添加 TapkuLibrary.bundle 资源文件 3.代码中完成实例,数据初始化就可以用了 739 下载修改后的版本。下次有时间在整理一个工程版本出来。 740 让 iPhone 屏幕常亮不变暗的方法 741 如果您希望运行自己开发的 App 时,iPhone 的屏幕不再自动变暗,可以使用以下方法 让屏幕常亮: iPhone OS 用一个布尔值用来控制是否取消应用程序空闲时间: @property(nonatomic, getter=isIdleTime 742 如果您希望运行自己开发的 App 时,iPhone 的屏幕不再自动变暗,可以使用以下方法 让屏幕常亮: 743  744 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 745 iPhone OS 用一个布尔值用来控制是否取消应用程序空闲时间:@property(nonatomic, getter=isIdleTimerDisabled) BOOL idleTimerDisabled。这个值的默认属性是"NO"。当大多数 应用程序没有接收到用户输入信息的时候,系统会把设备设置成“休眠”状态,iPhone 屏幕 也会变暗。这样做是为了保存更多电量。事实上,应用程序在运行加速度游戏的时候是不需 要用户输入的,当然这里只是一个假设,把这个变量设置为"YES",来取消系统休眠的“空 闲时间”。 746 重点是:你必须当真正需要的时候才打开这个属性当你不用的时候马上还愿成"NO"。 大多数应用程序在休眠时间到的时候让系统关闭屏幕。这个包括了有音频的应用程 序。在 Audio Session Services 中使用适当的回放和记录功能不会被间断当屏幕关闭时。只有地图应 用程序,游戏或者一些不间断的用户交互程序可以取消这个属性。 747 苹果开发网络编程知识总结 748 以下苹果开发网络编程知识由 CocoaChina 会员 cocoa_yang 总结,希望能为苹果开发 新手梳理知识脉络,节省入门时间。一:确认网络环境 3G/WIFI 1. 添加源文件和 framework 开发 Web 等网络应用程序 749 以下苹果开发网络编程知识由 CocoaChina 会员 “cocoa_yang” 总结,希望能为苹 果开发新手梳理知识脉络,节省入门时间。 750 一:确认网络环境 3G/WIFI 751 1. 添加源文件和 framework 752 开发 Web 等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没 有处理它们,是不会通过 Apple 的审查的。 753 Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。要在应用程序程 序中使用 Reachability,首先要完成如下两部: 754 1.1. 添加源文件: 755 在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图: 756 1.2.添加 framework: 757 将 SystemConfiguration.framework 添加进工程。如下图: 758 2. 网络状态 759 Reachability.h 中定义了三种网络状态: typedef enum { 760 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 761 NotReachable = 0, ReachableViaWiFi, ReachableViaWWAN 762 } NetworkStatus; 763 因此可以这样检查网络状态: 764 //无连接 765 //使用 3G/GPRS 网络 766 //使用 WiFi 网络 767 Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”]; switch ([r currentReachabilityStatus]) { 768 case NotReachable: 769 // 没有网络连接 770 break; 771 case ReachableViaWWAN: 772 // 使用 3G 网络 773 break; 774 case ReachableViaWiFi: 775 // 使用 WiFi 网络 break; 776 } 3.检查当前网络环境 777 程序启动时,如果想检测可用的网络环境,可以像这样 // 是否 wifi 778 + (BOOL) IsEnableWIFI { 779 return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); 780 } 781 // 是否 3G 782 + (BOOL) IsEnable3G { 783 return ([[Reachability currentReachabilityStatus] != NotReachable); 784 } 785 例子: 786 - (void)viewWillAppear:(BOOL)animated { 787 reachabilityForInternetConnection] 788 if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) && 789 NotReachable)) { 790 ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == 791 self.navigationItem.hidesBackButton = YES; [self.navigationItem setLeftBarButtonItem:nil animated:NO]; 792 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 793 } } 794 4. 链接状态的实时通知 网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变 795 化时,需要及时地通知用户: 796 Reachability 1.5 版本 797 // My.AppDelegate.h #import "Reachability.h" 798 @interface MyAppDelegate : NSObject <UIApplicationDelegate> { NetworkStatus remoteHostStatus; 799 } 800 @property NetworkStatus remoteHostStatus; 801 @end 802 // My.AppDelegate.m #import "MyAppDelegate.h" 803 @implementation MyAppDelegate @synthesize remoteHostStatus; 804 // 更新网络状态 805 - (void)updateStatus { 806 self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; } 807 // 通知网络状态 808 - (void)reachabilityChanged:(NSNotification *)note { 809 [self updateStatus]; 810 if (self.remoteHostStatus == NotReachable) { 811 UIAlertView *alert = initWithTitle:NSLocalizedString(@"AppName", nil) 812 [[UIAlertView 813 alloc] 814 [alert show]; 815 [alert release]; } 816 message:NSLocalizedString (@"NotReachable", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 817 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 818 } 819 // 程序启动器,启动网络监视 820 - (void)applicationDidFinishLaunching:(UIApplication *)application { 821 // 设置网络检测的站点 822 [[Reachability sharedReachability] setHostName:@"www.apple.com"]; [[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES]; 823 // 设置网络状态变化时的通知函数 824 [[NSNotificationCenter defaultCenter] addObserver:self 825 selector:@selector(reachabilityChanged:) 826 name:@"kNetworkReachabilityChangedNotification" object:nil]; [self updateStatus]; 827 } 828 - (void)dealloc { 829 // 删除通知对象 830 [[NSNotificationCenter defaultCenter] removeObserver:self]; [window release]; 831 [super dealloc]; 832 } 833 Reachability 2.0 版本 834 // MyAppDelegate.h @class Reachability; 835 @interface MyAppDelegate : NSObject <UIApplicationDelegate> { Reachability *hostReach; 836 } @end 837 // MyAppDelegate.m 838 - (void)reachabilityChanged:(NSNotification *)note { 839 Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); NetworkStatus status = [curReach currentReachabilityStatus]; 840 if (status == NotReachable) { 841 retain]; 842 // 监测网络情况 843 [[NSNotificationCenter defaultCenter] addObserver:self 844 selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; 845 hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] 846 hostReach startNotifer]; 847 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 848 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"" message:@"NotReachable" 849 delegate:nil 850 cancelButtonTitle:@"YES" otherButtonTitles:nil]; [alert show]; 851 [alert release]; 852 } } 853 - (void)applicationDidFinishLaunching:(UIApplication *)application { // ... 854 // ... } 855 二:使用 NSConnection 下载数据 856 1.创建 NSConnection 对象,设置委托对象 857 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; 858 [NSURLConnection connectionWithRequest:request delegate:self]; 859 2. NSURLConnection delegate 委托方法 860 - (void)connection:(NSURLConnection *)connection 861 didReceiveResponse:(NSURLResponse *)response; 862 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError 863 *)error; *)data; 864 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData 865 - (void)connectionDidFinishLoading:(NSURLConnection *)connection; 3. 实现委托方法 866 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 867 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 868 // store data 869 [self.receivedData setLength:0]; //通常在这里先清空接受数据的缓 870 存 871 } 872 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { /* appends the new data to the received data */ 873 [self.receivedData appendData:data]; //可能多次收到数据,把新的数据 添加在现有数据最后 874 } 875 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 876 // 错误处理 } 877 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // disconnect 878 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 879 NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; 880 NSLog(returnString); 881 [self urlLoaded:[self urlString] data:self.receivedData]; firstTimeDownloaded = YES; 882 } 883 三:使用 NSXMLParser 解析 xml 文件 884 1. 设置委托对象,开始解析 885 NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; 使用 initWithContentsOfURL 直接下载文件,但是有一个原因不这么做: 886 //或者也可以 887 // It\'s also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable 888 // because it gives less control over the network, particularly in responding to connection errors. 889 [parser setDelegate:self]; [parser parse]; 890 2. 常用的委托方法 891 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 892 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 893 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict; 894 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 895 qualifiedName:(NSString *)qName; 896 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; 897 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError; static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml"; 898 3. 应用举例 899 - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error { 900 NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL]; [parser setDelegate:self]; 901 [parser setShouldProcessNamespaces:NO]; 902 [parser setShouldReportNamespacePrefixes:NO]; 903 [parser setShouldResolveExternalEntities:NO]; [parser parse]; 904 NSError *parseError = [parser parserError]; 905 if (parseError && error) { 906 *error = parseError; } 907 [parser release]; } 908 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 909 attributes:(NSDictionary *)attributeDict{ // 元素开始句柄 910 if (qName) { 911 elementName = qName; 912 } 913 if ([elementName isEqualToString:@"user"]) { 914 // 输出属性值 915 NSLog(@"Name is %@ , Age objectForKey:@"name"], [attributeDict objectForKey:@"age"]); 916 } } 917 is %@", 918 [attributeDict 919 qualifiedName:(NSString*)qName 920 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 921 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 922 { 923 // 元素终了句柄 924 if (qName) { 925 elementName = qName; 926 } } 927 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 928 // 取得元素的 text } 929 NSError *parseError = nil; 930 [self parseXMLFileAtURL:[NSURL parseError:&parseError]; 931 如何隐藏状态栏 932 [ UIApplication sharedApplication ].statusBarHidden = YES; 933 .m 文件与.mm 文件的区别 934 .m 文件是 object-c 文件 935 .mm 文件相当于 c++或者 c 文件 936 URLWithString:feedURLString] 937 NSLog(@"afd")与 NSLog("afd") 938 细微差别会导致程序崩溃。 但是我不太明白为何苹果要把编译器做的对这两种常量有区别。 不过值得一提的是可能为了方便苹果自身的 NSObject 对象的格式化输出。 safari 其实没有把内存的缓存写到存储卡上 939 NSURLCache doesn\'t seem to support writing to disk on iPhone. The documentation for NSCachedURLResponse says that the NSURLCacheStoragePolicy "NSURLCacheStorageAllowed" is treated as "NSURLCacheStorageAllowedInMemoryOnly" by iPhone OS. 940 官方文档是这么说的。 941 qualifiedName:(NSString *)qName 942 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 943  为了证明这个,我找到了一个目录。 944 /private/var/mobile/Library/Caches/Safari/Thumbnails 945 随机数的使用 946 头文件的引用 947 #import <time.h> 948 #import <mach/mach_time.h> 949 srandom()的使用 950 srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF)); 951 直接使用 random() 来调用随机数 在 UIImageView 中旋转图像 952 float rotateAngle = M_PI; 953 CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle); imageView.transform = transform; 954 以上代码旋转 imageView, 角度为 rotateAngle, 方向可以自己测试哦! 955 在 Quartz 中如何设置旋转点 956 UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]]; 957 imageView.layer.anchorPoint = CGPointMake(0.5, 1.0); 这个是把旋转点设置为底部中间。记住是在QuartzCore.framework中才得到支 958 持。 959 NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; //NSDictionary, NSData 等文件可以直接转化为 plist 文件 960 NSDictionary *innerDict; NSString *name; 961 Player *player; 962 创建.plist 文件并存储 963 NSString *errorDesc; //用来存放错误信息 965 NSInteger saveIndex; 966 for(int i = 0; i < [playerArray count]; i++) { player = nil; 967 player = [playerArray objectAtIndex:i]; if(player == nil) 968 break; 969 name = player.playerName;// This "Player1" denotes the player name could 970 also be the computer name 971 innerDict = [self getAllNodeInfoToDictionary:player]; 972 [rootObj setObject:innerDict forKey:name]; // This "Player1" denotes the person who start this game 973 } 974 player = nil; NSData 975 dataFromPropertyList:(id)rootObj errorDescription:&errorDesc]; 976 *plistData 977 = [NSPropertyListSerialization format:NSPropertyListXMLFormat_v1_0 978 红色部分可以忽略,只是给 rootObj 添加一点内容。这个 plistData 为创建好的 plist 文件,用其 writeToFile 方法就可以写成文件。下面是代码: 979 /*得到移动设备上的文件存放位置*/ 980 NSString *documentsPath = [self getDocumentsDirectory]; 981 NSString *savePath = [documentsPath 982 stringByAppendingPathComponent:@"save.plist"]; 983 /*存文件*/ 984 if (plistData) { 985 [plistData writeToFile:savePath atomically:YES]; } 986 else { 987 NSLog(errorDesc); 988 [errorDesc release]; 989 } 990 - (NSString *)getDocumentsDirectory { 991 NSArray *paths 992 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0]; 993 } 994 读取 plist 文件并转化为 NSDictionary 997 NSString *documentsPath = [self getDocumentsDirectory]; 998 NSString *fullPath stringByAppendingPathComponent:@"save.plist"]; 999 NSMutableDictionary* plistDict initWithContentsOfFile:fullPath]; 1000 读取一般性文档文件 1001 = [documentsPath 1002 NSString *tmp; 1003 NSArray *lines; /*将文件转化为一行一行的*/ 1004 lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] 1005 componentsSeparatedByString:@"\n"]; NSEnumerator *nse = [lines objectEnumerator]; 1006 // 读取<>里的内容 1007 while(tmp = [nse nextObject]) { 1008 } 1009 = [[NSMutableDictionary 1010 alloc] 1011 NSString *stringBetweenBrackets = nil; 1012 NSScanner *scanner = [NSScanner scannerWithString:tmp]; [scanner scanUpToString:@"<" intoString:nil]; 1013 [scanner scanString:@"<" intoString:nil]; 1014 [scanner scanUpToString:@">" intoString:&stringBetweenBrackets]; 1015 NSLog([stringBetweenBrackets description]); 1016 对于读写文件,还有补充,暂时到此。随机数和文件读写在游戏开发中经常用到。所 以把部分内容放在这,以便和大家分享,也当记录,便于查找。 1017 隐藏 NavigationBar 1018 [self.navigationController setNavigationBarHidden:YES animated:YES]; 1019 在想隐藏的 ViewController 中使用就可以了。 1020 如何在 iPhone 程序中调用外部命令 1021 下面是如何在 iPhone 非官方 SDK 程序中调用外部命令的方法。 1022 - ( NSString * ) executeCommand : ( NSString * ) cmd { NSString * output = [ NSString string ] ; FILE * pipe = popen ( [ cmd cStringUsingEncoding : NSASCIIStringEnc 1024 下面是如何在 iPhone 非官方 SDK 程序中调用外部命令的方法。 1025 - (NSString *)executeCommand: (NSString *)cmd { 1026 NSString *output = [NSString string]; 1027 FILE *pipe = popen([cmd cStringUsingEncoding: NSASCIIStringEncoding], "r"); if (!pipe) return; 1028 char buf[1024]; 1029 while(fgets(buf, 1024, pipe)) { 1030 output = [output stringByAppendingFormat: @"%s", buf]; 1031 } 1032 pclose(pipe); return output; } 1033 NSString *yourcmd = [NSString stringWithFormat: @"your command"]; [self executeCommand: yourcmd]; 1034 如何在 iPhone 程序读取数据时显示进度窗 1035 下面代码说明如何使用 iPhone 非官方 SDK 在读取数据时显示进度条。 以下代码参考了 MobileRss。 1036 定义头文件: 1037 #import "uikit/UIProgressHUD.h" 1038 @interface EyeCandy : UIApplication { UIProgressHUD *progress; 1039 } 1040 - (void) showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)v withRect:(struct CGRect)rect; 1041 - (void) hideProgressHUD; .@end 上面的引号要改成<>。 1042 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 1043 import "EyeCandy.h" 1044 @implementation EyeCandy 1045 - (void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)v withRect:(struct CGRect)rect 1046 { 1047 progress = [[UIProgressHUD alloc] initWithWindow: w]; [progress setText: label]; 1048 [progress drawRect: rect]; 1049 [progress show: YES]; 1050 [v addSubview:progress]; } 1051 - (void)hideProgressHUD { 1052 [progress show: NO]; 1053 [progress removeFromSuperview]; } 1054 @end 1055 使用下面代码调用: 1056 // Setup Eye Candy View 1057 _eyeCandy = [[[EyeCandy alloc] init] retain]; 1058 // Call loading display 1059 [_eyeCandy showProgressHUD:@"Loading ..." withWindow:window withView:mainView withRect:CGRectMake(0.0f, 100.0f, 320.0f, 50.0f)]; 1060 // When finished for hiding the "loading text" [_eyeCandy hideProgressHUD]; 1061 WebKit 的基本用法 1062 WebKit 是苹果开发中比较常用的浏览器引擎,Safari 使用的正是 WebKit 引擎。WebKit 基于 KDE 的 KHTML 加以再开发,解析速度超过了以往所有的浏览器。这里简单记录一下 WebKit 的基本用法。 1063 WebKit 由下面的结构组成: 1064 更多苹果移动应用开发入门精选文档教程荟萃:http://down.51cto.com/zt/2401 1065 •DomCore •JavaScriptCore •WebCore 一般浏览 1066 要打开网页,可以这样做: 1067 1.[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]]; 1068 DomCore 1069 DomCore 用于处理 DOM 文档,包括: 1070 •DOMDocument 1071 •DOMNamedNodeMap 1072 •DOMNode 1073 •DOMNodeList 1074 要获取一个 DOMDocument,可以这样做: 1075 1.DOMDocument *myDOMDocument = [[webView mainFrame] DOMDocument]; 1076 要用于 HTML 处理,可以使用 DOMHTMLDocument(Mac OS X 10.4 之后),获取方式 相同: 1077 1.DOMHTMLDocument *myDOMDocument = (DOMHTMLDocument*)[[webView mainFrame] DOMDocument]; 1078 方法定义: 1079 苹果的 WebKit 更新说明 JavaScriptCore 1080 在 WebKit 中执行脚本的方法: 1081 1.WebScriptObject *myscript = [webView windowScriptObject]; 2.NSString *script = @"alert(\'hello\');"; 1082 3.[myscript evaluateWebScript script]; 1083 参考: 1084 http://www.macgood.com/thread-24636-1-1.html http://www.cocoadev.com/index.pl?WebKit 1086 为什么不要做 iPhone 上面的应用 1087 简单来说就是因为两国的文化不同,或者说生活方式的不同。美国不管多穷的人都有 车,他们平时的生活方式和国内绝对是完全不同的。做应用和做游戏不一样,应用需要满足 人们某一 1088 简单来说就是因为两国的文化不同,或者说生活方式的不同。美国不管多穷的人 都有车,他们平时的生活方式和国内绝对是完全不同的。做应用和做游戏不一样,应用需要 满足人们某一部分的需求,比如,一个计算小费的软件,在国内不会有市场,可是美国人都 有一个。 1089 大家可以设身处地的想一下,谁会需要你做的软件,这样的人有多少,这样的人又有 iPhone 的又有多少。 1090 对于应用来说,针对商务人士的又比针对普通人的好,基本上商务人士不太在乎几块 钱一个软件,这也是 backup assistant 卖得最好的一个原因。这个软件一年的年费 24 美元, 大约有数千万美元一年的收入。什么样的应用软件是这些人需要的?连笔者自己也不太清 楚,笔者虽然已经在美国工作了多年,但是对于美国文化的了解还处于一知半解状态,更不 用说正在留学的学生了。 1091 还有一个能成功的应用软件是你已经有非常多的数据,比如你有当地的所有加油站的 信息,做一个油价的地图软件,显然市场会不错。不过数据要是美国的数据,国内的没有太 大的帮助。 1092 综上所述,游戏比应用好做很多,如果要作应用的话,可以从单机的小应用开始。要 在美国运营一个支持 10 万人的网络应用,没有 30 万美元绝对没戏。如果非要上,只能早死 早超生了。 1093 获取 iPhone 用户手机号 1094 使用下面的函数可以返回用户的手机号: 1095 extern NSString *CTSettingCopyMyPhoneNumber(); 1096 然后调用即可。 1097 由于这个函数是包含在 CoreTelephony 中,所以只能用于非官方 iPhone SDK。 1098 在程序中关闭 iPhone 1099 首先在程序中引用 #include sys/reboot.h 然后使用 reboot(RB_HALT); 就可以直接将 iPhone 关机。 1100 首先在程序中引用 1101 1102 #include <sys/reboot.h> 1103 然后使用 1104 reboot(RB_HALT); 1105 就可以直接将 iPhone 关机。 1106 convert the contents of an NSData object to an NSString 1107 1. NSString *stringFromASC = [NSString stringWithCString:[ascData bytes] length:[ascData length]]; 1108 If the NSData object contains unichar characters then do this: 1109 NSString *stringFromUnichar = [NSString stringWithCharacters:[unicharData bytes] length:[unicharData length] / sizeof(unichar)]; 1110 2. - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding 1111 iPhone 的特殊 URL 1112 在 iPhone 中,可以直接用 UIApp 打开 URL 地址。如下所示: 1113 1.[ UIApp openURL: [ NSURL URLWithString:@"http://www.apple.com" ] ]; 1114 或者: 1115 1.[ UIApp openURL: [ NSURL URLWithString:@"mailto:apple@mac.com?Subject=hello" ] ]; 1116 与此同时,iPhone 还包含一些其他除了 http://或者 mailto:之外的 URL: sms:// 可以调用短信程序 1117 tel:// 可以拨打电话 1118 itms:// 可以打开 MobileStore.app 1119 audio-player-event:// 可以打开 iPod audio-player-event://?uicmd=show-purchased-playlist 可以打开 iPod 播放列表 video-player-event:// 可以打开 iPod 中的视频 1121 get iphone uniqueIdentifier 1122 I also find that I can get uniqueIdentifier using: 1123 UIDevice *myDevice = [UIDevice currentDevice];NSString *identifier = myDevice.uniqueIdentifier; 1124 打开本地网页,与远程网页 1125 fileURLWithPath:Initializes and returns a newly created NSURL object as a file URL with a specified path. 1126 + (id)fileURLWithPath:(NSString *)path 1127 URLWithString: 1128 Creates and returns an NSURL object initialized with a provided string. 1129 + (id)URLWithString:(NSString *)URLString 1130 教你如何使用 UIWebView 1131 Start by opening up the WebBrowserTutorialAppDelegate.h file and editing the @interface 1132 line to read: 1133 @interface WebBrowserTutorialAppDelegate : NSObject <UIWebViewDelegate> { 1134 What we have done is to make the main AppDelegate a delegate for the UIWebView as well. 1135 Now we need to set our webView to have the main AppDelegate as its delegate, you can do this by opening up WebBrowserTutorialAppDelegate.m and putting the following line just inside theapplicationDidFinishLaunching function: 1136 webView.delegate = self; 1137 That is all pretty self explanatory, it just sets the delegate of our webView to self, which in this case is our main application delegate. 1138 Now we are pretty much done, we just need to add the function to catch the link clicks. To do this we need to add a new function, copy the content below to the WebBrowserTutorialAppDelegate.m file: 1139 - (BOOL)webView:(UIWebView*)webView 1141 shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { 1142 NSURL *url = request.URL; 1143 NSString *urlString = url.absoluteString; NSLog(urlString); 1144 return YES; 1145 } 1146 This function will catch all requests and allow you to either manipulate them and pass them on or to perform your own custom action and stop the event from bubbling. 1147 The first line gets the URL of the request, this is the contents inside the href attribute in the anchor tag. 1148 The next line converts the URL to a string so we can log it out. You can access many parts of the NSURL, here are some of them and brief description of what they do. 1149 * absoluteString - An absolute string for the URL. Creating by resolving the receiver’s string against its base. 1150 * absoluteURL - An absolute URL that refers to the same resource as the receiver. If the receiver is already absolute, returns self. 1151 * baseURL - The base URL of the receiver. If the receiver is an absolute URL, returns nil. 1152 * host - The host of the URL. 1153 * parameterString - The parameter string of the URL. 1154 * password - The password of the URL (i.e. http://user:pass@www.test.com would return 1155 pass) 1156 * path - Returns the path of a URL. 1157 * port - The port number of the URL. 1158 * query - The query string of the URL. 1159 * relativePath - The relative path of the URL without resolving against the base URL. If the 1160 receiver is an absolute URL, this method returns the same value as path. 1161 * relativeString - string representation of the relative portion of the URL. If the receiver is an 1162 absolute URL this method returns the same value as absoluteString. 1163 * scheme - The resource specifier of the URL (i.e. http, https, file, ftp, etc). * user - The user portion of the URL. 1164 Then the third line simply logs the URL to the console, so you will new to open up the console while you run this in the simulator to see the results. 1165 Finally the forth line returns YES, this will allow the UIWebView to follow the link, if you would just like to catch a link and stop the UIWebView from following it then simply return NO. 1166 UIBUtton title image 不能同时显示 1168 [ leftbutton setTitle:_(@"About") forState:UIControlStateNormal ]; 1169 [ leftbutton setImage:image forState:UIControlStateNormal ]; 1170 不能同时显示。 其他控件如:UINavigatonItem 1171 不要在语言包里面设置空格 1172 有时,为了界面的需要,我们不要在语言包里面加空格,要在程序中进行控制。 1173 buttonTitle = [ NSString stringWithFormat:@" %@", _(@"updateWeb") ]; 1174 NSNotificationCenter 带参数发送 1175 MPMoviePlayerController* theMovie = [[MPMoviePlayerController 1176 alloc]initWithContentURL:[NSURL fileURLWithPath:[[[tableTitles objectAtIndex:row] objectAtIndex:3] ]]; 1177 [[NSNotificationCenter defaultCenter] selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie]; 1178 [theMovie play]; -(void)myMovieFinishedCallback:(NSNotification*)aNotification { 1179 MPMoviePlayerController *theMovie = [aNotification object]; 1180 [[NSNotificationCenter defaultCenter] name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie]; 1181 // Release the movie instance [theMovie release]; } 1182 ------------ 1183 MPMoviePlayerController* theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:[[[tableTitles objectForKey:keyIndex] 1184 objectForKey:keyIndex] 1185 addObserver:self 1186 removeObserver:self 1188 objectAtIndex:row] objectAtIndex:3] ]]; 1189 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie userInfo:dic]; 1190 [theMovie play]; 1191 -(void)myMovieFinishedCallback:(NSNotification*)aNotification 1192 { 1193 MPMoviePlayerController *theMovie = [aNotification object]; 1194 [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie]; 1195 // Release the movie instance [theMovie release]; 1196 } 1197 延时一段时间执行某一函数 1198 [self performSelector:@selector(dismissModal) withObject:self afterDelay:1.0]; 1199 无 99 美金证书联机开发 1200 第一步:进入 cd /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.1.sdk/ sudo vi SDKSettings.plist,将 CODE_SIGNING_REQUIRED 的值改成 NO. 保存后退出. 1201 第二步:重新启动 XCode 项目. 1202 第三步:右击项目 GetInfo.将 Code Signing 下的 Code Signing Identity 值设置成 Don\'t Code 1203 Sign, 将 Code Signing Identity 下的 Any iOS Device 的值设置成空. 1204 获取 IOS 设备的基本信息 系统唯一标识 1205 是什么设备:iPad 还是 iPhone 等 iOS 版本号 1206 系统名称 1207 [[UIDevice currentDevice] uniqueIdentifier], 1209 [[UIDevice currentDevice] localizedModel], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] model]]; 1210 用 NSDateFormatter 调整时间格式的代码 1211 在开发 iOS 程序时,有时候需要将时间格式调整成自己希望的格式,这个时候我们可 以用 NSDateFormatter 类来处理。 1212 例如: 1213 //实例化一个 NSDateFormatter 对象 1214 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 1215 //设定时间格式,这里可以设置成自己需要的格式 1216 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 1217 //用[NSDate date]可以获取系统当前时间 1218 NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]]; 1219 //输出格式为:2010-10-27 10:22:13 1220 NSLog(@”%@”,currentDateStr); 1221 //alloc 后对不使用的对象别忘了 release 1222 [dateFormatter release]; 1223 UIView 设置成圆角方法 1224 m_mainImgView.layer.cornerRadius = 6; m_mainImgView.layer.masksToBounds = YES; 1225 iPhone 里的 frame 和 bounds 区别 1234 所有内存管理的原则全在这里! 1235 简单??哈哈! 1236 名人曰:“大道至简” 这儿玩意儿说起来比过家家还容易,但其实有些事情真正做起来并不是简单的事儿~~ 1237 咱们首先来说怎么样才能成为一个对象的拥有者。Cocoa 提供了一个机制叫"reference counting",翻译过来就是“关联记数器”(自己翻译的,真不知叫啥,如果有官方的翻译请 通知我)。每一个对象都有一个关联记数的值。当它被创建时,它的值为“1”。当值减少到 “0”时,就会被回收(调用它的 deallocate 方法,如果没有写,则调用从 NSObject 继承而来 的回收方法,下文有说,一定要重写该方法)。以下几个方法可以操作这个记数: 1238 1,alloc 为对象分配内存,记数设为“1”,并返回此对象。 1239 2,copy 复制一个对象,此对象记数为“1”,返回此对象。你将成为此克隆对象的拥有者 1240 3,retain 对象“关联记数”加“1”,并成为此对象的拥有者。 1241 4,release 对象“关联记数”减“1”,并丢掉此对象。 1242 5,autorelease 在未来的某一时刻,对象“关联记数”减“1”。并在未来的某个时间放弃此对象。 1243 有了上面的几个方法(当然这也是所有的内存操作的方法,简单吧,哈哈哈)你就可 以随意操作一个对象的记数。并部分或完全的控制它的生命周期。但实际应用中,随意乱写 上面的任何一个方法都可能会带来严重的内存泄露。混乱的内存分配等于没完没了的麻烦工 作,你不想在情人节的日子还在为记数之类的鸟问题而丢了老婆吧~~哈哈哈,为了美丽温 柔贤惠又善解人意的准老婆请牢记以下四条: 1244 1,一个代码块内要确保 copy, alloc 和 retain 的使用数量与 release 和 autorelease 的 数量。 1245 2,在使用以“alloc”或“new”开头或包含“copy”的方法,或“retain”一个对象时, 你就会变为它的拥有者。 1247 3,实现“dealloc”方法,并施放所有的实例变量。(其实这里还有很多的巧儿门!!) 4,永不自己调用“dealloc”方法,这是系统当“retain”减到“0”时,自动调用的。 1248 手动调用会引起 retain count 记数错误(多一次的 release)。 其实做到这些也不难, 1249 retain count 增加与减少的方法对应,板丁板做到了就行了。 来自:http://blog.csdn.net/dboylx/archive/2009/02/13/3888746.aspx iphone 更改键盘右下角按键的 type 1250 以 UISearchBar 为例。 1251 创建 mySearchBar: 1252 mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, SEARCH_HEIGHT)]; 1253 mySearchBar.placeholder = curPath; [mySearchBar setDelegate:self]; //tableView.tableHeaderView =mySearchBar; [self.view addSubview:mySearchBar]; 1254 0,320, 1255 更改按键的 keyType(默认是 return,这里将它更改成 done,当然还可以更改成其他的): UITextField *searchField = [[mySearchBar subviews] lastObject]; 1256 [searchField setReturnKeyType:UIReturnKeyDone]; 1257 [mySearchBar release];
版权声明:本文为Ruby-Hua原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。