常用語句

//設(shè)置尺寸為屏幕尺寸的時(shí)候
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

//隨機(jī)數(shù)
inputValues[i] = arc4random();
//plist 加載控制器
NSString *stringVC = _Mydictionary[@"first"][@"pushVC"][row];
UIViewController VC = [[NSClassFromString(stringVC) alloc] init];
VC.navigationItem.title = _Mydictionary[@"first"][@"title"][row];
[self.navigationController pushViewController:VC animated:YES];
方法二,控制器跳轉(zhuǎn)
/
NSString *demoClassString = [NSString stringWithFormat:@"DemoVC%ld", indexPath.row];
[self.navigationController pushViewController:[NSClassFromString(demoClassString) new] animated:YES];
*/

iphone中獲取屏幕分辨率的方法

CGRect rect = [[UIScreen mainScreen] bounds];
CGSize size = rect.size;
CGFloat width = size.width;
CGFloat height = size.height;

Array數(shù)組的寫入和讀出

按鈕只有一個(gè)被選中,寫入全局變量

只有一個(gè)被選中的其他方法()

  btn.selected = YES;

for (UIButton *subBtn in self.array4Btn) {
    if (subBtn != btn) {
        subBtn.selected = NO;
    }
}

-(void)buttonSelected:(UIButton*)sender{
if (_tmpBtn == nil){
sender.selected = YES;
_tmpBtn = sender;
}
else if (_tmpBtn !=nil && _tmpBtn == sender){
sender.selected = YES;

}
else if (_tmpBtn!= btn && _tmpBtn!=nil){
    _tmpBtn.selected = NO;
    sender.selected = YES;
    _tmpBtn = btn;
}

}

iOS 一句話移除所有子控件

[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

1、NSCalendar用法
-(NSString *) getWeek:(NSDate *)d
{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekCalendarUnit;
NSDateComponents *components = [calendar components:units
fromDate:d];
[calendar release];
switch ([components weekday]) {
case1:
return @"Monday"; break;
case2:
return @"Tuesday"; break;
case3:
return @"Wednesday"; break;
case4:
return @"Thursday"; break;
case5:
return @"Friday"; break;
case6:
return @"Saturday"; break;
case7:
return @"Sunday"; break;
default:
return @"NO Week"; break;
}
NSLog(@"%@",components);
}

2、將網(wǎng)絡(luò)數(shù)據(jù)讀取為字符串
-(NSString *)getDataByURL:(NSString *)url {
return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}

3、讀取?絡(luò)圖?
-(UIImage *)getImageByURL:(NSString *)url {
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}

4、多線程(這種方式,只管建立線程,不管回收線程)
[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];
-(void)scheduleTask
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release];
}

如果有參數(shù),則這么?
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];
-(void)scheduleTask:(NSDate *)mdate
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; }

在線程?運(yùn)?主線程?的?法
[self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];

5、?戶缺省值NSUserDefaults讀取:
NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
NSArray *languages = [df objectForKey:@"AppleLanguages"];
NSLog(@"all language is %@",languages);
NSLog(@"index is %@",[languages objectAtIndex:0]);
NSLocale *currentLocale = [NSLocale currentLocale];
NSLog(@"language Code is %@",[currentLocale objectForKey:NSLocaleLanguageCode]);
NSLog(@"Country Code is %@",[currentLocale objectForKey:NSLocaleCountryCode]);

6、view之間轉(zhuǎn)換的動(dòng)態(tài)效果設(shè)置
SecondViewController *secondViewController = [[SecondViewController alloc] init];
secondViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//?水平翻轉(zhuǎn)
[self.navigationController presentModalViewController:secondViewController animated:YES];
[secondViewController release];

7、UIScrollView 滑動(dòng)用法: -(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(@"正在滑動(dòng)中。。")
}
//?戶直接滑動(dòng)UIScrollView,可以看到滑動(dòng)條
-(void)scrollViewDidEndDelerating:(UIScrollView *)scrollView {
}
//通過其他控件觸發(fā)UIScrollView滑動(dòng),看不到滑動(dòng)條
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
}
//UIScrollView 設(shè)置滑動(dòng)不超出本?身范圍
[scrollView setBounces:NO];

8、iphone的系統(tǒng)目錄:
//得到Document:目錄
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到temp臨時(shí)目錄
NSString *temPath = NSTemporaryDirectory();
//得到目錄上的文件地址
NSString *address = [paths stringByAppendingPathComponent:@"1.rtf"];

9、狀態(tài)欄顯?示indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

10、app Icon顯示數(shù)字:

  • (void)applicationDidEnterBackground:(UIApplication *)application
    {

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];
}
11、sqlite保存地址:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *filePath = [thePath stringByAppendingPathComponent:@"kilometer.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePathstringByAppendingPathComponent:@"kilometer2.sqlite"];

12、鍵盤彈出隱藏,textfield變位置
_tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100,
150, 260, 30)];
_tspasswordTF.backgroundColor = [UIColor redColor];
_tspasswordTF.tag = 2;
/*
Use this method to release shared resources, save user data,
_tspasswordTF.delegate = self;
[self.window addSubview: _tspasswordTF];

  • (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self animateTextField: textField up: YES];
    }

  • (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self animateTextField: textField up: NO];
    [textField resignFirstResponder];
    return YES;
    }

  • (void) animateTextField: (UITextField*) textField up: (BOOL) up {
    const int movementDistance = 80;
    // tweak as needed
    const float movementDuration = 0.3f;
    // tweak as needed
    int movement = (up ? -movementDistance : movementDistance);
    [UIView beginAnimations: nil context: nil]; [UIView setAnimationBeginsFromCurrentState: YES]; [UIView setAnimationDuration: movementDuration];
    self.window.frame = CGRectOffset(self.window.frame, 0, movement);
    [UIView commitAnimations];
    }

13、獲取圖片的尺?
CGImageRef img = [imageView.image CGImage];
NSLog(@"%d",CGImageGetWidth(img));
NSLog(@"%d",CGImageGetHeight(img));

14、AlertView,ActionSheet的cancelButton點(diǎn)擊事件:

  • (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex; // before animation and hiding view
    {
    NSLog(@"cancel alertView... buttonindex = %d",buttonIndex); //當(dāng)?用戶按下Cancel按鈕
    if (buttonIndex == [alertView cancelButtonIndex]){
    exit(0);
    }
    }
  • (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
    {
    NSLog(@"%s %d button = %d cancel actionSheet.....",FUNCTION,LINE, buttonIndex);
    //當(dāng)?用戶按下Cancel按鈕
    if (buttonIndex == [actionSheet cancelButtonIndex]) {
    exit(0);
    }
    }
    15、給window設(shè)置全局背景圖片
    self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@""]];

16、tabcontroller隨意切換tabbar
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
或者
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
或者
_tabBarController.selectedIndex = tabIndex;

17、計(jì)算字符串?度:
CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size: 18]].width;

18、計(jì)算點(diǎn)到線段的最短距離
根據(jù)結(jié)果坐標(biāo)使?用CLLocation類的函數(shù)計(jì)算實(shí)際距離。 double
x1, y1, x2, y2, x3, y3;
double px =x2 -x1;
double py = y2 -y1;
double som = px px + py py;
double u =((x3 - x1)
px +(y3 - y1)
py)/som; if(u > 1)
{ u=1; }
if (u < 0) { u =0;
}
//the closest point
double x = x1 + u px; double y = y1 + u * py; double dx = x - x3; double dy = y - y3;
double dist = sqrt(dx
dx + dy*dy);

19、UISearchBar背景透明
在使用UISearchBar時(shí),將背景?設(shè)定為clearColor,或者將translucent設(shè)為YES,都
不能使背景透明,經(jīng)過一番研究,發(fā)現(xiàn)了一種超級(jí)簡(jiǎn)單和實(shí)用的?法:
[[searchbar.subviews objectAtIndex:0] removeFromSuperview];
背景完全消除了,只剩下搜索框本身了。

20、圖像與緩存 :
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"icon.png"]]; // 會(huì)緩存圖片
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不會(huì)緩存圖?片

21、iphone對(duì)視圖層的操作
// 將textView的邊框設(shè)置為圓角
_textView.layer.cornerRadius = 8;
_textView.layer.masksToBounds = YES;
//給textView添加一個(gè)有色邊框
_textView.layer.borderWidth = 5;
_textView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09
blue:0.07 alpha:1] CGColor];
//textView添加背景圖片
_textView.layer.contents = (id)[UIImage imageNamed:@"31"].CGImage;

22、關(guān)閉當(dāng)前應(yīng)用
[[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];

23、給iPhone程序添加歡迎界面
1、將你需要的歡迎界面的圖片,存成Default.png
[NSThread sleepForTimeInterval:10.0]; 這樣歡迎頁面就停留10秒后消失了。

24、NSString NSDate轉(zhuǎn)換
NSString* myString= @"testing";
NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncodi ng]];
NSString* aStr =
[[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];

25、UIWebView中的dataDetectorTypes
如果你希望在瀏覽頁面時(shí),頁面上的電話號(hào)碼顯示成鏈接形式,點(diǎn)擊電話號(hào)碼就撥打電話,這時(shí)你就需要用到dataDetectorTypes了。

NSURL *url = [NSURL URLWithString:@"http://2015.iteye.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
[webView loadRequest:requestObj];

26、打開蘋果電腦瀏覽器的代碼
如您想在 Mac 軟件中集成一鍵打開瀏覽器功能,可以使用以下代碼

[[NSWorkspace sharedWorkspace] openURLs: urls withAppBundleIdentifier:@"com.apple.Safari"
options: NSWorkspaceLaunchDefault additionalEventParamDescriptor: NULL launchIdentifiers: NULL];

27、設(shè)置StatusBar以及NavigationBar的樣式
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque; self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

28、隱藏Status Bar 你可能知道一個(gè)簡(jiǎn)易的方法,那就是在程序的viewDidLoad中加入以下代碼:

[UIApplication sharedApplication].statusBarHidden = YES;
此法可以隱藏狀態(tài)條,但問題在于,狀態(tài)條所占空間依然無法為程序所用。
本篇介紹的方法依然簡(jiǎn)單,但更為奏效。通過簡(jiǎn)單的3個(gè)步驟,在plist中加入一 個(gè)鍵值來實(shí)現(xiàn)。

  1. 點(diǎn)擊程序的Info.plist
  2. 右鍵點(diǎn)擊任意一處,選擇Add Row
  3. 加入的新鍵值,命名為UIStatusBarHidden或者Status bar is initially hidden,然后選上這一項(xiàng)。

29、產(chǎn)生隨機(jī)數(shù)的最佳方案
arc4random()會(huì)返回一個(gè)整型數(shù),因此,返回1至100的隨機(jī)數(shù)可以這樣寫:
arc4random()%100 + 1;

30、string 和char轉(zhuǎn)換
NSString *cocoaString = [[NSString alloc] initWithString:@"MyString"];
const char *myCstring = [cocoaString cString];
const char *cString = "Hello";
NSString *cocoString = [[NSString alloc] initWithCString:cString];

  1. String Class 的轉(zhuǎn)化
    NSString *stringVC = _Mydictionary[@"first"][@"pushVC"][row];
    UIViewController *VC = [[NSClassFromString(stringVC) alloc] init];
    VC.navigationItem.title = _Mydictionary[@"first"][@"title"][row];
    [self.navigationController pushViewController:VC animated:YES];

31、用UIWebView在當(dāng)前程序中打開網(wǎng)頁 如果URL中帶中文的話,必須將URL中的中文轉(zhuǎn)成URL形式的才行。
NSString *query = [NSString stringWithFormat:@"http://www.baidu.com?q=蘋 果"];
NSString *strUrl = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];

32、阻止ios設(shè)備鎖屏
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

[UIApplication sharedApplication].idleTimerDisabled = YES;

33、一條命令卸載Xcode和 iPhone SDK
sudo /Developer/Library/uninstall-devtools --mode=all

34、獲取按鈕的title
-(void)btnPressed:(id)sender {
NSString *title = [sender titleForState:UIControlStateNormal];
NSString *newText = [[NSString alloc] initWithFormat:@"%@",title];
label.text = newText;
[newText release];
}

35、NSDate to NSString
NSString *dateStr = [[NSString alloc] initWithFormat:@"%@", date];
或者
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];

36、圖片由小到大緩慢顯示的效果
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
[imageView setImage:[UIImage imageNamed:@"4.jpg"]];
self.ANImageView = imageView;
[self.view addSubview:imageView];
[imageView release];
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:2.5];
CGImageRef img = [self.ANImageView.image CGImage];
[ANImageView setFrame:CGRectMake(0, 0, CGImageGetWidth(img), CGImageGetHeight(img))];
[UIView commitAnimations];
NSLog(@"%lu",CGImageGetWidth(img));
NSLog(@"%lu",CGImageGetHeight(img));

37、數(shù)字轉(zhuǎn)字符串
NSString *newText = [[NSString alloc] initWithFormat:@"%d",number];
numberlabel.text = newText;
[newText release];

38、隨機(jī)函數(shù)arc4random() 的使用.
在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的 最大值則是 0x100000000 (4294967296),從而有更好的精度。使用 arc4random()還不需要生成隨機(jī)種子,因?yàn)榈谝淮握{(diào)用的時(shí)候就會(huì)自動(dòng)生成。
如:
arc4random() 來獲取0到100之間浮點(diǎn)數(shù)

define ARC4RANDOM_MAX 0x100000000

double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);

  1. self.view.backgroundColor = [UIColor colorWithHue: arc4random() % 2 55 / 255

saturation: arc4random() % 2 brightness: arc4random() % 2
alpha: 1.0];

39、改變鍵盤顏色的實(shí)現(xiàn)
iPhone和iPod touch的鍵盤顏色其實(shí)是可以通過代碼更改的,這樣能更匹配 App的界面風(fēng)格,下面是改變iPhone鍵盤顏?色的代碼。
-(void)textFieldDidBeginEditing:(UITextField *)textField {
NSArray *ws = [[UIApplication sharedApplication] windows];
for(UIView *w in ws)
{
NSArray *vs = [w subviews];
for(UIView *v in vs)
{

if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIPeripheralHostView"])
{
v.backgroundColor = [UIColor blueColor];
} }
} }
55 / 255 55 / 255
_textField.keyboardAppearance = UIKeyboardAppearanceAlert;//有這個(gè)設(shè)置屬性 才起作用

40、iPhone上實(shí)現(xiàn)Default.png動(dòng)畫 添加一張和Default.png?一樣的圖片,對(duì)這個(gè)圖片進(jìn)行動(dòng)畫,從而實(shí)現(xiàn)Default動(dòng)畫的漸變消 失的效果。
UIImageView *splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
splashView.image = [UIImage imageNamed:@"Default.png"];
[self.window addSubview:splashView];
[self.window bringSubviewToFront:splashView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:
self.window cache:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:cont ext:)];
splashView.alpha = 0.0;
splashView.frame = CGRectMake(-60, -85, 440, 635);
[UIView commitAnimations];

41、將EGO主題色添加到xcode中 打開終端,執(zhí)行以下命令
Shell代碼

  1. mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; 2. cd ~/Library/Application\ Support/Xcode/Color\ Themes;
  2. curl -O http://developers.enormego.com/assets/egotheme/
    EGO.xccolortheme
    然后,重啟Xcode,選擇Preferences > Fonts & Colors,最后從Color Theme 中選擇EGO即可。

42、將圖片保存到圖片庫(kù)中
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount]== 1)
{
UIImageWriteToSavedPhotosAlbum([ANImageView image], nil, nil, nil);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存儲(chǔ)照?片 message:@"您已將照?存于圖片庫(kù)中,打開照片程序即可查" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];
[alert release];
}
}

43、讀取plist文件
//取得文件路徑
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"文件
名" ofType:@"plist"];
//讀取到一個(gè)字典
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//讀取到一個(gè)數(shù)組
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];

44、使用#pragma mark 加上這樣的標(biāo)識(shí)后,在導(dǎo)航條上會(huì)顯示源文件上方法列表,這樣就可對(duì)功能相關(guān)的方法進(jìn)行分隔,方便查看了。
設(shè)置UITabBarController默認(rèn)的啟動(dòng)Item //a tabBar
UITabBarController *tabBarController = [[UITabBarController alloc] init];
NSArray *controllers = [NSArray arrayWithObjects: nav1, nav2, nav3, nav4, nil];
tabBarController.viewControllers = controllers; tabBarController.selectedViewController = nav2;

45、NSUserDefaults的使用
NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
NSUInteger selectedIndex = 1;
[store setInteger:selectedIndex forKey:@"selectedIndex"];
if ([store valueForKey:@"selectedIndex"] != nil) {
NSInteger index = [store integerForKey:@"selectedIndex"];
NSLog(@"?用戶已經(jīng)設(shè)置的selectedIndex的值是:%d", index);
}
else {
NSLog(@"請(qǐng)?jiān)O(shè)置默認(rèn)的值");
}

46、更改Xcode的缺省公司名 在終端中執(zhí)行以下命令:
defaults write com.apple.Xcode PBXCustomTemplateMacroDefiniti ons '{"ORGANIZATIONNAME" = "COMPANY";}'

47、設(shè)置uiView,成圓角矩形 畫個(gè)圓角的矩形沒啥難的,有兩種方法:
1 。直接修改view的樣式,系統(tǒng)提供好的了:
view.layer.cornerRadius = 6;
view.layer.masksToBounds = YES; 用layer做就可以了,十分簡(jiǎn)單。這個(gè)需要倒庫(kù) QuartzCore.framework;

  1. 在view 里面畫圓角矩形 CGFloat radius = 20.0;
    CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1);
    CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx =
    CGRectGetMaxX(rect);
    CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy =
    CGRectGetMaxY(rect);
    CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFill);
    用畫筆的方法,在drawRect里面做。

48、畫圖時(shí)圖片倒轉(zhuǎn)解決方法
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, self.bounds.size.height); CGContextScaleCTM(context, 1, -1);
drawImage = [UIImage imageNamed:@"12.jpg"];
CGImageRef image = CGImageRetain(drawImage.CGImage);
CGContextDrawImage(context, CGRectMake(30.0, 200, 450, 695), image); CGContextRestoreGState(context);

49、Nsstring 自適應(yīng)文本寬高度
CGSize feelSize = [feeling sizeWithFont:[UIFont systemFontOfSize:12]
constrainedToSize:CGSizeMake(190, 200)];
float feelHeight = feelSize.height;

50、用HTTP協(xié)議,獲取www.baidu.com網(wǎng)站的HTML數(shù)據(jù):
[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]];

51、viewDidLoad中設(shè)置按鈕圖案
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, 60, 30);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

UIImage *buttonImageNormal = [UIImage imageNamed:@"huifu-001.png"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal
stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[button setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; UIImage *buttonImagePressed = [UIImage imageNamed:@"qyanbuhuifu-001.png"];
UIImage *stretchableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[button setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];
52、鍵盤上的return鍵改成Done: textField.returnKeyType = UIReturnKeyDone;

53、textfield設(shè)置成為密碼框: [textField_pwd setSecureTextEntry:YES];

54、收回鍵盤: [textField resignFirstResponder]; 或者 [textfield addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditin gDidEndOnExit];
55、振動(dòng):

import<AudioToolbox/AudioToolbox.h> //需加頭文件

方法一: AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
方法二: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 當(dāng)設(shè)備不支持方法一函數(shù)時(shí),起蜂鳴作用, 而方法二支持所有設(shè)備

56、用Cocoa刪除文件:
NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager removeFileAtPath: tildeFilename handler: nil];

57、UIView透明漸變與移動(dòng)效果:
//動(dòng)畫配制開始
[UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:2.5];
//圖片上升動(dòng)畫
CGRect rect = imgView.frame ;
rect.origin.y = 30;
imgView.frame = rect;
//半透明度漸變動(dòng)畫
imgView.alpha = 0;
//提交動(dòng)畫
[UIView commitAnimations];

58、在UIView的drawRect方法內(nèi),用Quartz2D API繪制一個(gè)像素寬的水平直線:
-(void)drawRect:(CGRect)rect{
//獲取圖形上下文
CGContextRef context = UIGraphicsGetCurrentContext(); //設(shè)置圖形上下文的路徑繪制顏色 CGContextSetStrokeColorWithColor(context, [UIColor
whiteColor].CGColor); //取消防鋸齒
CGContextSetAllowsAntialiasing(context, NO); //添加線
CGContextMoveToPoint(context, 50, 50);
CGContextAddLineToPoint(context, 100, 50); //繪制
CGContextDrawPath(context, kCGPathStroke); }

59、用UIWebView加載: www.baidu.com
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[web loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:web];
[web release];

60、利用UIImageView實(shí)現(xiàn)動(dòng)畫:

  • (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *fishAni=[[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    [self.view addSubview:fishAni];
    [fishAni release];
    //設(shè)置動(dòng)畫幀
    fishAni.animationImages=[NSArray arrayWithObjects: [UIImage imageNamed:@"1.jpg"],
    [UIImage imageNamed:@"2.jpg"],
    [UIImage imageNamed:@"3.jpg"],
    [UIImage imageNamed:@"4.jpg"],
    [UIImage imageNamed:@"5.jpg"],nil ];
    //設(shè)置動(dòng)畫總時(shí)間 fishAni.animationDuration=1.0;
    //設(shè)置重復(fù)次數(shù),0表示不重復(fù) fishAni.animationRepeatCount=0;
    //開始動(dòng)畫
    [fishAni startAnimating]; }

61、用NSTimer做一個(gè)定時(shí)器,每隔1秒執(zhí)行一次 pressedDone;
-(IBAction)clickBtn:(id)sender{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printHello) userInfo:nil repeats:YES];
[timer fire];
}

62、利用蘋果機(jī)里的相機(jī)進(jìn)行錄像:
-(void) choosePhotoBySourceType: (UIImagePickerControllerCameraCaptureMode) sourceType {
m_imagePickerController = [[[UIImagePickerController alloc] init] autorelease];
m_imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
m_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; m_imagePickerController.cameraDevice =UIImagePickerControllerCameraDeviceFront;
//m_imagePickerController.cameraCaptureMode =UIImagePickerControllerCameraCaptureModeVideo;
NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:m_imagePickerController.sourceType];
if ([sourceTypes containsObject:(NSString *)kUTTypeMovie ]) {
m_imagePickerController.mediaTypes= [NSArray arrayWithObjects: (NSString *)kUTTypeMovie,(NSString *)kUTTypeImage,nil];
}
// m_imagePickerController.cameraCaptureMode = sourceType; //m_imagePickerController.mediaTypes //imagePickerController.allowsEditing = YES;
[self presentModalViewController: m_imagePickerController animated:YES];
}

-(void) takePhoto {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[self choosePhotoBySourceType:nil];
} }
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

  • (void)viewDidLoad {
    [super viewDidLoad];
    UIButton takePhoto = [UIButton
    buttonWithType:UIButtonTypeRoundedRect];
    [takePhoto setTitle:@"錄像" forState:UIControlStateNormal];
    [takePhoto addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    takePhoto.frame = CGRectMake(50,100,100,30); [self.view addSubview:takePhoto];
    }
    63、App中調(diào)用 iPhone的home + 電源鍵截屏功能
    // 前置聲明是消除警告
    CGImageRef UIGetScreenImage();
    CGImageRef img = UIGetScreenImage();
    UIImage
    scImage=[UIImage imageWithCGImage:img]; UIImageWriteToSavedPhotosAlbum(scImage, nil, nil, nil);

64、切割圖片的方法
//切割圖片
UIImage *image = [UIImage imageNamed:@"7.jpg"];
//設(shè)置需要截取的?大?小
CGRect rect = CGRectMake(20, 50, 280, 200);
//轉(zhuǎn)換
CGImageRef imageRef = image.CGImage;
//截取函數(shù)
CGImageRef imageRefs = CGImageCreateWithImageInRect(imageRef, rect);
//生成uIImage
UIImage *newImage = [[UIImage alloc] initWithCGImage:imageRefs];
//添加到imageView中
imageView = [[UIImageView alloc] initWithImage:newImage];
imageView.frame = rect;

65、如何屏蔽父view的touch事件
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path,NULL,0,0);
CGRect rect = CGRectMake(0, 100, 320, 40); CGPathAddRect(path, NULL, rect); if(CGPathContainsPoint(path, NULL, point, NO)) {
[self.superview touchesBegan:nil withEvent:nil]; }
CGPathRelease(path);
return self;
}

66、用戶按home鍵推送通知
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pressHome:) name:UIApplicationDidEnterBackgroundNotification object:app];
-(void)pressHome:(NSNotification *)notification {
NSLog(@"pressHome...");
}

67、在UIImageView中旋轉(zhuǎn)圖像:
float rotateAngle = M_PI; //M_PI為一角度
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateA ngle);
imageView.transform = transform;

68、隱藏狀態(tài)欄:
方法一, [UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
方法二, 在應(yīng)用程序的Info.plist 文件中將 UIStatusBarHidden 設(shè)置為YES;

69、構(gòu)建多個(gè)可拖動(dòng)視圖:
@interface DragView: UIImageView{
CGPoint startLocation;
NSString *whichFlower; }
@property (nonatomic ,retain)NSString *whichFlower; @end
@implementation DragView
@synthesize whichFlower;

  • (void) touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event{ CGPoint pt = [[touhes anyObject ] locationInView:self]; startLocation = pt;
    [[self superview] bringSubviewToFront:self];
    }
  • (void) touchesMoved:(NSSet *)touches withEvent:( UIEvent *)event{
    CGPoint pt = [[touches anyObject] locatonInView:self]; CGRect frame = [self frame];
    frame.origin.x += pt.x – startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [self setFrame:frame]; }
    @end
    @interface TestController :UIViewController{
    UIView *contentView;
    }
    @end
    @implementation TestController

define MAXFLOWERS 16

CGPoint randomPoint(){
return CGPointMake(random()%6 , random()96);
}

  • (void)loadView{
    CGRect apprect = [[UIScreen mainScreen] applicationFrame];
    contentView = [[UIView alloc] initWithFrame :apprect];
    contentView.backgroundColor = [UIColor blackColor];
    self.view = contentView;
    [contentView release];
    for(int i=0 ; i<MAXFLOWERS; i++){
    CGRect dragRect = CGRectMake(0.0f ,0.0f, 64.0f ,64.0f);
    dragRect.origin = randomPoint();
    DragView *dragger = [[DragView alloc] initWithFrame:dragRect];
    [dragger setUserInteractionEnabled: YES];
    NSString *whichFlower = [[NSArray arrayWithObjects:@”blueFlower.png”,@”pinkFlower.png”,nil] objectAtIndex: ( random() %2)];
    [dragger setImage:[UIImage imageNamed:whichFlower]];
    [contentView addSubview :dragger];
    [dragger release];
    } }
  • (void)dealloc{
    [contentView release];
    [super dealloc];
    }
    @end

70、iPhone中加入dylib庫(kù)
加入dylib庫(kù)時(shí),必須在info中加入頭文件路徑。/usr/include/庫(kù)名(不要后綴)

71、iPhone iPad 中App名字如何支持多語言和顯示自定義名字
建立InfoPlist.strings,本地化此文件,然后在文件內(nèi)添加: CFBundleDisplayName = "xxxxxxxxxxx"; //
這樣應(yīng)?用程序就能顯示成設(shè)置的名字“xxxxxxxxxxx”.

72、在數(shù)字鍵盤上添加button:
//定義一個(gè)消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//addObserver:注冊(cè)一個(gè)觀察員 name:消息名稱

  • (void)keyboardWillShow:(NSNotification )note {
    // create custom button
    UIButton doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    [doneButton setImage:[UIImage imageNamed:@"5.png"]
    forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
    // locate keyboard view
    UIWindow
    tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    //返回應(yīng)用程序window
    UIView
    keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++)
    //遍歷window上的所有 subview
    {
    keyboard = [tempWindow.subviews objectAtIndex:i];
    // keyboard view found;
    add the custom button to it
    if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
    [keyboard addSubview:doneButton];
    }
    }
    73、去掉iPhone應(yīng)用圖標(biāo)上的弧形高光 有時(shí)候我們的應(yīng)用程序不需要在圖標(biāo)上加上默認(rèn)的高光,可以在你的應(yīng)用的 Info.plist中加入:
    Icon already includes gloss effects YES

74、實(shí)現(xiàn)修改navigation的back按鈕
self.navigationItem.backBarButtonItem =
[[[UIBarButtonItem alloc] initWithTitle: NSLocalizedStringFromTable (@"返回", @"System", nil) style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];

75、給圖片加上陰影
UIImageViewpageContenterImageView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"onePageApple.png"]];
//添加邊框
CALayer
layer = [pageContenterImageView layer];
layer.borderColor= [[UIColor whiteColor]CGColor];
layer.borderWidth=0.0f;
//添加四個(gè)邊陰影
pageContenterImageView.layer.shadowColor= [UIColor blackColor].CGColor;
pageContenterImageView.layer.shadowOffset=CGSizeMake(0,0); pageContenterImageView.layer.shadowOpacity=0.5; pageContenterImageView.layer.shadowRadius=5.0; 陰影渲染會(huì)嚴(yán)重消耗內(nèi)存 ,導(dǎo)致程序咔嘰.
/陰影效果/
//添加邊框
CALayer*layer = [self.pageContenter layer];
layer.borderColor= [[UIColorwhiteColor]CGColor];
layer.borderWidth=0.0f;
//添加四個(gè)邊陰影
self.pageContenter.layer.shadowColor= [UIColorblackColor].CGColor;//陰影顏色
self.pageContenter.layer.shadowOffset=CGSizeMake(0,0);//陰影偏移 self.pageContenter.layer.shadowOpacity=0.5;//陰影不透明度 self.pageContenter.layer.shadowRadius=5.0;//陰影半徑
?二、給視圖加上陰影
UIView * content=[[UIView alloc] initWithFrame:CGRectMake(100, 250, 503, 500)];
content.backgroundColor=[UIColor orangeColor];
//content.layer.shadowOffset=10;
content.layer.shadowOffset = CGSizeMake(5, 3); content.layer.shadowOpacity = 0.6; content.layer.shadowColor = [UIColor blackColor].CGColor;
[self.window addSubview:content];

76、UIView有一個(gè)屬性,clipsTobounds 默認(rèn)情況下是NO, 如果,我們想要view2把超出的那部份隱藏起來的話,就得改變它的父視圖也 就view1的clipsTobounds屬性值。
view1.clipsTobounds = YES;
使用objective-c 建立UUID UUID是128位的值,它可以保證唯一性。通常,它是由機(jī)器本身網(wǎng)卡的MAC地
址和當(dāng)前系統(tǒng)時(shí)間來生成的。 UUID是由中劃線連接而成的字符串。例如:0A326293-BCDD-4788-8F2D-
C4D8E53C108B
在聲明文件中聲明一個(gè)方法:

import <UIKit/UIKit.h>

@interface UUIDViewController : UIViewController { }

  • (NSString *) createUUID;
    @end
    對(duì)應(yīng)的實(shí)現(xiàn)文件中實(shí)現(xiàn)該方法:
  • (NSString *) createUUID {
    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuidStr = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
    CFRelease(uuidObject);
    return uuidStr; }

77、iPhone iPad中橫屏顯示代碼
1、強(qiáng)制橫屏
[application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
2、在infolist?里?面加了Supported interface orientations這?一項(xiàng),增加之后添加四個(gè)item就是 ipad的四個(gè)?方向
item0 UIInterfaceOrientationLandscapeLeft
item1 UIInterfaceOrientationLandscapeRight 這表明只?支持橫屏顯?示 經(jīng)常讓人混淆迷惑的問題 - 數(shù)組和其他集合類

78、當(dāng)一個(gè)對(duì)象被添加到一個(gè)array, dictionary, 或者 set等這樣的集合類型中的時(shí)候,集合會(huì)retain它。 對(duì)應(yīng) 的,當(dāng)集合類被release的時(shí)候,它會(huì)發(fā)送對(duì)應(yīng)的release消息給包含在其中的對(duì)象。 因此,如果你想建立一 個(gè)包含一堆number的數(shù)組,你可以像下面示例中的幾個(gè)方法來做
NSMutableArray *array; int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [NSNumber numberWithInt: i];
[array addObject: n]; }
在這種情況下, 我們不需要retain這些number,因?yàn)閍rray將替我們這么做。 NSMutableArray *array;
int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [[NSNumber alloc] initWithInt: i];
[array addObject: n];
[n release];
}
在這個(gè)例子中,因?yàn)槟闶褂昧?alloc去建立了一個(gè)number,所以你必須顯式的-release它,以保證retain count的平衡。因?yàn)閷umber加入數(shù)組的時(shí)候,已經(jīng)retain它了,所以數(shù)組中的number變量不會(huì)被release

79、UIView動(dòng)畫停止調(diào)用方法遇到的問題
在實(shí)現(xiàn)UIView的動(dòng)畫的時(shí)候,并且使?用UIView來重復(fù)調(diào)?用它結(jié)束的回調(diào)時(shí)候要 注意以下?方法中的finished參數(shù)
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if([finishied boolValue] == YES)
//一定要判斷這句話,要不在程序中當(dāng)多個(gè)View刷新的時(shí)候,就可能出現(xiàn)動(dòng)畫異常的現(xiàn)象 {
//執(zhí)行想要的動(dòng)作 }
}

80、判斷在UIViewController中,viewWillDisappear的時(shí)候是push還是 pop出來

  • (void)viewWillDisappear:(BOOL)animated {
    NSArray *viewControllers = self.navigationController.viewControllers; if (viewControllers.count > 1 && [viewControllers
    objectAtIndex:viewControllers.count-2] == self) {
    // View is disappearing because a new view controller was pushed onto the
    stack
    NSLog(@"New view controller was pushed");
    } else if ([viewControllers indexOfObject:self] == NSNotFound) { // View is disappearing because it was popped from the stack NSLog(@"View controller was popped");
    } }

81、連接字符串小技巧
NSString *string1 = @"abc / cde";
NSString *string2 = @"abc" @"cde";
NSString *string3 = @"abc" "cde";
NSLog( @"string1 is %@" , string1 );
NSLog( @"string2 is %@" , string2 ); NSLog( @"string3 is %@" , string3 );
打印結(jié)果如下:
string1 is abc cde string2 is abccde

82、隨文字大小label自適應(yīng)
label=[[UILabel alloc] initWithFrame:CGRectMake(50, 23, 175, 33)];
label.backgroundColor = [UIColor purpleColor];
[label setFont:[UIFont fontWithName:@"Helvetica" size:30.0]];
[label setNumberOfLines:0];
//[myLable setBackgroundColor:[UIColor clearColor]]; [self.window addSubview:label];
NSString *text = @"this is ok";
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30.0];
CGSize size = [text sizeWithFont: font constrainedToSize: CGSizeMake(175.0f, 2000.0f) lineBreakMode: UILineBreakModeWordWrap];
CGRect rect= label.frame; rect.size = size;
[label setFrame: rect]; [label setText: text];

83、UILabel字體加粗
//加粗
lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; //加粗并且傾斜
lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];

84、為IOS應(yīng)用組件添加圓角的方法 具體的實(shí)現(xiàn)是使用QuartzCore庫(kù),下面我具體的描述一下實(shí)現(xiàn)過程:
? 首先創(chuàng)建一個(gè)項(xiàng)目,名字叫:ipad_webwiew
? 利?用Interface Builder添加?一個(gè)UIWebView,然后和相應(yīng)的代碼相關(guān)聯(lián) ? 添加QuartzCore.framework
代碼實(shí)現(xiàn): 頭?文件:

import <UIKit/UIKit.h>

import <QuartzCore/QuartzCore.h>

@interface ipad_webwiewViewController : UIViewController {
IBOutlet UIWebView *myWebView; UIView *myView;
}
@property (nonatomic,retain) UIWebView *myWebView; @end
代碼實(shí)現(xiàn):

  • (void)viewDidLoad {
    [super viewDidLoad]; //給圖層添加背景圖?片: //myView.layer.contents = (id)[UIImage
    imageNamed:@"view_BG.png"].CGImage; //將圖層的邊框設(shè)置為圓腳
    myWebView.layer.cornerRadius = 8; myWebView.layer.masksToBounds = YES; //給圖層添加?一個(gè)有?色邊框
    myWebView.layer.borderWidth = 5; myWebView.layer.borderColor = [[UIColor colorWithRed:0.52
    green:0.09 blue:0.07 alpha:1] CGColor]; }

85、實(shí)現(xiàn)UIToolBar的自動(dòng)消失
-(void)showBar
{
! [UIView beginAnimations:nil context:nil];
! [UIView setAnimationDuration:0.40];
! (_toolBar.alpha == 0.0) ? (_toolBar.alpha = 1.0) : (_toolBar.alpha = 0.0);
! [UIView commitAnimations];
}

  • (void)viewDidAppear:(BOOL)animated {
    [NSObject cancelPreviousPerfo rmRequestsWithTarget: self];
    [self performSelector: @selector(delayHideBars) withObject: nil afterDelay: 3.0];
    }
  • (void)delayHideBars { [self showBar];
    }

86、自定義UINavigationItem.rightBarButtonItem
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"remote",@"mouse",@"text",nil]];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"home_a.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"myletv_a.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(0, 0, 200, 30);
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:self action:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;
[segmentedControl release];
UINavigationController直接返回到根viewController
[self.navigationController popToRootViewControllerAnimated:YES];
想要從第五層直接返回到第二層或第三層,用索引的形式
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 2)] animated:YES];

87、鍵盤監(jiān)聽事件

ifdef __IPHONE_5_0

float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 5.0)
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

endif

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
-(void)keyboardWillShow:(NSNotification *)notification {
NSValue *value = [[notification userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
CGRect keyboardRect = [value CGRectValue]; NSLog(@"value %@ %f",value,keyboardRect.size.height); [UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
keyboardHeight = keyboardRect.size.height; self.view.frame = CGRectMake(0, -(251 - (480 - 64 -
keyboardHeight)), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations]; }

88、 ios6.0強(qiáng)制橫屏的方法:
在appDelegate里調(diào)用
if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
[[UIApplication sharedApplication]
setStatusBarOrientation:
UIInterfaceOrientationLandscapeRight animated:NO];
}

89、 返回按鈕去掉文字
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];

90、 導(dǎo)航欄 navigation 添加按鈕

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;

91、 post解析json數(shù)據(jù)
-(void) setUpDate
{
AFHTTPRequestOperationManager * mar = [AFHTTPRequestOperationManager manager];
NSMutableDictionary * parm = [NSMutableDictionary dictionary];
[mar POST:@"http://192.168.1.47:8080/EasternMedical/dComment/listJson.do" parameters:parm success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSDictionary * dict = responseObject;
    NSMutableArray * Muarray = [[NSMutableArray alloc]init];
    NSArray * hos = [dict objectForKey:@"rows"];
    NSLog(@"%@",hos);
    NSString *str2 = [NSString stringWithFormat:@"%@",self.Docterinf.name];
    for(NSDictionary * dict0 in hos)
    {
        SickInf * pital = [[SickInf alloc]init];

        //            NSString * str1 = @"http://192.168.1.47:8080/EasternMedical/";
        //            NSString * str2 = [str1 stringByAppendingString:dict0[@"image"]];
        //            pital.imageView = str2;
        NSString *str1 = dict0[@"doctorId"];

        if ([str2 isEqualToString: str1] ) {

            pital.name = dict0[@"infor"][@"user_name"];
            pital.sickComment = dict0[@"comments"];
            //            pital.sickTime = dict0[@"peoplenum"];
            pital.sickClass = dict0[@"disease"];
            pital.attitude = dict0[@"attitude"];
            pital.effect = dict0[@"effect"];
            pital.recommend = dict0[@"recommend"];
            // post 解析 時(shí)間
            float time = [dict0[@"commentstime"][@"time"] floatValue];
            NSDate * dt = [NSDate dateWithTimeIntervalSince1970:time / 1000];
            NSDateFormatter * df = [[NSDateFormatter alloc] init];
            [df setDateFormat:@"yyyy-MM-dd HH:mm"];
            pital.sickTime = [df stringFromDate:dt];


            [Muarray addObject:pital];

        }
               }
    self.CommetArray =  Muarray;
    [self NAVView];
    [self CreatScrollView];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"請(qǐng)求失敗");
}];

}
、、==================================================================================================
92,根據(jù)CLLocation得到coordinate(坐標(biāo))而后打開google地圖:
NSString *mapUrl=[NSString stringWithFormat:@"http://maps.google.com/maps?q=%f,%f",loc.latitude,loc.longitude];

NSURL *url=[NSURL URLWithString:mapUrl];

[[UIApplication sharedApplication] openURL:url];

93.日期格式化:

NSDataFormat *format=[NSDateFormat alloc] init];

[format setDateFormat:@"hh:mm:ss"];

NSDate *noew=[NSDate date];

NSString *str=[format stringFromDate:now];

94。通過通知調(diào)用方法:

UIApplication *app = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserve:self

selector:@selector(xxx:)

name:UIApplicationWillTerminateNofification

object:app];

95。遍歷所有視圖的方法:

其中cell是UITableViewCell,

for(UIView *oneView in cell.contentView.subviews)

{

if ([oneView isMemberOfClass:[UITextField class]])

{

textField = (UITextField *)oneView;

}

}

1、背景音樂播放 支持mp3格式 循環(huán)播放長(zhǎng)音樂

這種播放音樂的方式導(dǎo)入框架#import <AVFoundation/AVFoundation.h>;

NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"changan" ofType:@"mp3"]; //創(chuàng)建音樂文件路徑

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

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

//創(chuàng)建播放器

self.myBackMusic = thePlayer; //賦值給自己定義的類變量

[musicURL release];

[thePlayer release];

[myBackMusic prepareToPlay];

[myBackMusic setVolume:1]; //設(shè)置音量大小

myBackMusic.numberOfLoops = -1;//設(shè)置音樂播放次數(shù) -1為一直循環(huán)

if (mainMusicStatus)

{

[myBackMusic play]; //播放

}

2、按鈕播放聲音 播放短聲音

需要導(dǎo)入框架#import <AudioToolbox/AudioToolbox.h>

NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"Clapping Crowd Studio 01" ofType:@"caf"]; //創(chuàng)建音樂文件路徑

CFURLRef thesoundURL = (CFURLRef) [NSURL fileURLWithPath:thesoundFilePath];

AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID);

//變量SoundID與URL對(duì)應(yīng)

AudioServicesPlaySystemSound(sameViewSoundID); //播放SoundID聲音

97.設(shè)置UILabel換行

UILabel*label;
//設(shè)置換行
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
換行符還是n
比如NSString * xstring=@"lineonenlinetwo"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,818評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,185評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,656評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,647評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,446評(píng)論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,951評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,041評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,189評(píng)論 0 287
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,718評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,602評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,800評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,045評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,419評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評(píng)論 1 281
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,420評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,755評(píng)論 2 371

推薦閱讀更多精彩內(nèi)容