本文共 33684 字,大约阅读时间需要 112 分钟。
1、NSCalendar用法 -(NSString *) getWeek:(NSDate *)d
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekCalendarUnit;
NSDateComponents *components = [calendar components:units
switch ([components weekday]) {
return @"Tuesday"; break;
return @"Wednesday"; break;
return @"Thursday"; break;
return @"Saturday"; break;
return @"NO Week"; break;
-(NSString *)getDataByURL:(NSString *)url {
return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
-(UIImage *)getImageByURL:(NSString *)url {
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
4、多线程(这种方式,只管建立线程,不管回收线程)
[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];
-(void)scheduleTask:(NSDate *)mdate
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
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]);
SecondViewController *secondViewController = [[SecondViewController alloc] init];
secondViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//⽔水平翻转
[self.navigationController presentModalViewController:secondViewController animated:YES];
[secondViewController release];
7、UIScrollView 滑动用法: -(void)scrollViewDidScroll:(UIScrollView *)scrollView
//⽤户直接滑动UIScrollView,可以看到滑动条
-(void)scrollViewDidEndDelerating:(UIScrollView *)scrollView {
//通过其他控件触发UIScrollView滑动,看不到滑动条
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
//UIScrollView 设置滑动不超出本⾝身范围
[scrollView setBounces:NO];
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *temPath = NSTemporaryDirectory();
NSString *address = [paths stringByAppendingPathComponent:@"1.rtf"];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
- (void)applicationDidEnterBackground:(UIApplication *)application
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *filePath = [thePath stringByAppendingPathComponent:@"kilometer.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePathstringByAppendingPathComponent:@"kilometer2.sqlite"];
_tspasswordTF = [[UITextField alloc] initWithFrame: CGRectMake(100,
_tspasswordTF.backgroundColor = [UIColor redColor];
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];
- (void) animateTextField: (UITextField*) textField up: (BOOL) up {
const int movementDistance = 80;
const float movementDuration = 0.3f;
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];
CGImageRef img = [imageView.image CGImage];
NSLog(@"%d",CGImageGetWidth(img));
NSLog(@"%d",CGImageGetHeight(img));
14、AlertView,ActionSheet的cancelButton点击事件:
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex; // before animation and hiding view
NSLog(@"cancel alertView... buttonindex = %d",buttonIndex); //当⽤用户按下Cancel按钮
if (buttonIndex == [alertView cancelButtonIndex]){
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
NSLog(@"%s %d button = %d cancel actionSheet.....",__FUNCTION__,__LINE__, buttonIndex);
if (buttonIndex == [actionSheet cancelButtonIndex]) {
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;
CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size: 18]].width;
根据结果坐标使⽤用CLLocation类的函数计算实际距离。 double
double som = px *px + py *py;
double u =((x3 - x1)*px +(y3 - y1)*py)/som; if(u > 1)
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);
在使用UISearchBar时,将背景⾊设定为clearColor,或者将translucent设为YES,都
不能使背景透明,经过一番研究,发现了一种超级简单和实用的⽅法:
[[searchbar.subviews objectAtIndex:0] removeFromSuperview];
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"icon.png"]]; // 会缓存图片
UIImageView *wallpaper = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不会缓存图⽚片
_textView.layer.cornerRadius = 8;
_textView.layer.masksToBounds = YES;
_textView.layer.borderWidth = 5;
_textView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09
blue:0.07 alpha:1] CGColor];
_textView.layer.contents = (id)[UIImage imageNamed:@"31"].CGImage;
[[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
1、将你需要的欢迎界面的图片,存成Default.png
[NSThread sleepForTimeInterval:10.0]; 这样欢迎页面就停留10秒后消失了。
NSString* myString= @"testing";
NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncodi ng]];
[[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];
25、UIWebView中的dataDetectorTypes
如果你希望在浏览页面时,页面上的电话号码显示成链接形式,点击电话号码就拨打电话,这时你就需要用到dataDetectorTypes了。
NSURL *url = [NSURL URLWithString:@"http://2015.iteye.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
[webView loadRequest:requestObj];
如您想在 Mac 软件中集成一键打开浏览器功能,可以使用以下代码
[[NSWorkspace sharedWorkspace] openURLs: urls withAppBundleIdentifier:@"com.apple.Safari"
options: NSWorkspaceLaunchDefault additionalEventParamDescriptor: NULL launchIdentifiers: NULL];
27、设置StatusBar以及NavigationBar的样式
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque; self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
28、隐藏Status Bar 你可能知道一个简易的方法,那就是在程序的viewDidLoad中加入以下代码:
[UIApplication sharedApplication].statusBarHidden = YES;
此法可以隐藏状态条,但问题在于,状态条所占空间依然无法为程序所用。
本篇介绍的方法依然简单,但更为奏效。通过简单的3个步骤,在plist中加入一 个键值来实现。
3. 加入的新键值,命名为UIStatusBarHidden或者Status bar is initially hidden,然后选上这一项。
arc4random()会返回一个整型数,因此,返回1至100的随机数可以这样写:
NSString *cocoaString = [[NSString alloc] initWithString:@"MyString"];
const char *myCstring = [cocoaString cString];
const char *cString = "Hello";
NSString *cocoString = [[NSString alloc] initWithCString:cString];
31、用UIWebView在当前程序中打开网页 如果URL中带中文的话,必须将URL中的中文转成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];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
[UIApplication sharedApplication].idleTimerDisabled = YES;
33、一条命令卸载Xcode和 iPhone SDK
sudo /Developer/Library/uninstall-devtools --mode=all
-(void)btnPressed:(id)sender {
NSString *title = [sender titleForState:UIControlStateNormal];
NSString *newText = [[NSString alloc] initWithFormat:@"%@",title];
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]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
[imageView setImage:[UIImage imageNamed:@"4.jpg"]];
self.ANImageView = imageView;
[self.view addSubview:imageView];
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));
NSString *newText = [[NSString alloc] initWithFormat:@"%d",number];
numberlabel.text = newText;
在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的 最大值则是 0x100000000 (4294967296),从而有更好的精度。使用 arc4random()还不需要生成随机种子,因为第一次调用的时候就会自动生成。
arc4random() 来获取0到100之间浮点数
#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
iPhone和iPod touch的键盘颜色其实是可以通过代码更改的,这样能更匹配 App的界面风格,下面是改变iPhone键盘颜⾊色的代码。
-(void)textFieldDidBeginEditing:(UITextField *)textField {
NSArray *ws = [[UIApplication sharedApplication] windows];
NSArray *vs = [w subviews];
if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIPeripheralHostView"])
v.backgroundColor = [UIColor blueColor];
_textField.keyboardAppearance = UIKeyboardAppearanceAlert;//有这个设置属性 才起作用
40、iPhone上实现Default.png动画 添加一张和Default.png⼀一样的图片,对这个图片进行动画,从而实现Default动画的渐变消 失的效果。
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:
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:cont ext:)];
splashView.frame = CGRectMake(-60, -85, 440, 635);
[UIView commitAnimations];
41、将EGO主题色添加到xcode中 打开终端,执行以下命令
1. mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; 2. cd ~/Library/Application\ Support/Xcode/Color\ Themes;
3. curl -O http://developers.enormego.com/assets/egotheme/
然后,重启Xcode,选择Preferences > Fonts & Colors,最后从Color Theme 中选择EGO即可。
-(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:@"存储照⽚片 message:@"您已将照⽚存于图片库中,打开照片程序即可查" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"文件
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
44、使用#pragma mark 加上这样的标识后,在导航条上会显示源文件上方法列表,这样就可对功能相关的方法进行分隔,方便查看了。
设置UITabBarController默认的启动Item //a tabBar
UITabBarController *tabBarController = [[UITabBarController alloc] init];
NSArray *controllers = [NSArray arrayWithObjects: nav1, nav2, nav3, nav4, nil];
tabBarController.viewControllers = controllers; tabBarController.selectedViewController = nav2;
NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
NSUInteger selectedIndex = 1;
[store setInteger:selectedIndex forKey:@"selectedIndex"];
if ([store valueForKey:@"selectedIndex"] != nil) {
NSInteger index = [store integerForKey:@"selectedIndex"];
NSLog(@"⽤用户已经设置的selectedIndex的值是:%d", index);
46、更改Xcode的缺省公司名 在终端中执行以下命令:
defaults write com.apple.Xcode PBXCustomTemplateMacroDefiniti ons '{"ORGANIZATIONNAME" = "COMPANY";}'
47、设置uiView,成圆角矩形 画个圆角的矩形没啥难的,有两种方法:
view.layer.cornerRadius = 6;
view.layer.masksToBounds = YES; 用layer做就可以了,十分简单。这个需要倒库 QuartzCore.framework;
2. 在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 =
CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy =
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);
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);
CGSize feelSize = [feeling sizeWithFont:[UIFont systemFontOfSize:12]
constrainedToSize:CGSizeMake(190, 200)];
float feelHeight = feelSize.height;
50、用HTTP协议,获取www.baidu.com网站的HTML数据:
[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]];
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设置成为密码框: [textField_pwd setSecureTextEntry:YES];
54、收回键盘: [textField resignFirstResponder]; 或者 [textfield addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditin gDidEndOnExit];
#import<AudioToolbox/AudioToolbox.h> //需加头文件
方法一: AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
方法二: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 当设备不支持方法一函数时,起蜂鸣作用, 而方法二支持所有设备
NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager removeFileAtPath: tildeFilename handler: nil];
[UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:2.5];
CGRect rect = imgView.frame ;
[UIView commitAnimations];
58、在UIView的drawRect方法内,用Quartz2D API绘制一个像素宽的水平直线:
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext(); //设置图形上下文的路径绘制颜色 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];
UIImageView *fishAni=[[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
[self.view addSubview:fishAni];
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 ];
//设置动画总时间 fishAni.animationDuration=1.0;
//设置重复次数,0表示不重复 fishAni.animationRepeatCount=0;
[fishAni startAnimating]; }
61、用NSTimer做一个定时器,每隔1秒执行一次 pressedDone;
-(IBAction)clickBtn:(id)sender{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printHello) userInfo:nil repeats:YES];
-(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];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
[self choosePhotoBySourceType:nil];
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
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中调用 iPhone的home + 电源键截屏功能
CGImageRef UIGetScreenImage();
CGImageRef img = UIGetScreenImage();
UIImage* scImage=[UIImage imageWithCGImage:img]; UIImageWriteToSavedPhotosAlbum(scImage, nil, nil, nil);
UIImage *image = [UIImage imageNamed:@"7.jpg"];
CGRect rect = CGRectMake(20, 50, 280, 200);
CGImageRef imageRef = image.CGImage;
CGImageRef imageRefs = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *newImage = [[UIImage alloc] initWithCGImage:imageRefs];
imageView = [[UIImageView alloc] initWithImage:newImage];
-(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]; }
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pressHome:) name:UIApplicationDidEnterBackgroundNotification object:app];
-(void)pressHome:(NSNotification *)notification {
float rotateAngle = M_PI; //M_PI为一角度
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateA ngle);
imageView.transform = transform;
方法一, [UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
方法二, 在应用程序的Info.plist 文件中将 UIStatusBarHidden 设置为YES;
@interface DragView: UIImageView{
@property (nonatomic ,retain)NSString *whichFlower; @end
- (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;
@interface TestController :UIViewController{
@implementation TestController
return CGPointMake(random()%6 , random()96);
CGRect apprect = [[UIScreen mainScreen] applicationFrame];
contentView = [[UIView alloc] initWithFrame :apprect];
contentView.backgroundColor = [UIColor blackColor];
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];
加入dylib库时,必须在info中加入头文件路径。/usr/include/库名(不要后缀)
71、iPhone iPad 中App名字如何支持多语言和显示自定义名字
建立InfoPlist.strings,本地化此文件,然后在文件内添加: CFBundleDisplayName = "xxxxxxxxxxx"; //
这样应⽤用程序就能显示成设置的名字“xxxxxxxxxxx”.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//addObserver:注册一个观察员 name:消息名称
- (void)keyboardWillShow:(NSNotification *)note {
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];
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
for(int i=0; i<[tempWindow.subviews count]; i++)
keyboard = [tempWindow.subviews objectAtIndex:i];
add the custom button to it
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
73、去掉iPhone应用图标上的弧形高光 有时候我们的应用程序不需要在图标上加上默认的高光,可以在你的应用的 Info.plist中加入:
Icon already includes gloss effects YES
self.navigationItem.backBarButtonItem =
[[[UIBarButtonItem alloc] initWithTitle: NSLocalizedStringFromTable (@"返回", @"System", nil) style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];
UIImageView*pageContenterImageView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"onePageApple.png"]];
CALayer*layer = [pageContenterImageView layer];
layer.borderColor= [[UIColor whiteColor]CGColor];
pageContenterImageView.layer.shadowColor= [UIColor blackColor].CGColor;
pageContenterImageView.layer.shadowOffset=CGSizeMake(0,0); pageContenterImageView.layer.shadowOpacity=0.5; pageContenterImageView.layer.shadowRadius=5.0; 阴影渲染会严重消耗内存 ,导致程序咔叽.
CALayer*layer = [self.pageContenter layer];
layer.borderColor= [[UIColorwhiteColor]CGColor];
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有一个属性,clipsTobounds 默认情况下是NO, 如果,我们想要view2把超出的那部份隐藏起来的话,就得改变它的父视图也 就view1的clipsTobounds属性值。
view1.clipsTobounds = YES;
使用objective-c 建立UUID UUID是128位的值,它可以保证唯一性。通常,它是由机器本身网卡的MAC地
址和当前系统时间来生成的。 UUID是由中划线连接而成的字符串。例如:0A326293-BCDD-4788-8F2D-
@interface UUIDViewController : UIViewController { }
- (NSString *) createUUID;
- (NSString *) createUUID {
CFUUIDRef uuidObject = CFUU reate(kCFAllocatorDefault);
NSString *uuidStr = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
[application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
2、在infolist⾥里⾯面加了Supported interface orientations这⼀一项,增加之后添加四个item就是 ipad的四个⽅方向
item0 UIInterfaceOrientationLandscapeLeft
item1 UIInterfaceOrientationLandscapeRight 这表明只⽀支持横屏显⽰示 经常让人混淆迷惑的问题 - 数组和其他集合类
78、当一个对象被添加到一个array, dictionary, 或者 set等这样的集合类型中的时候,集合会retain它。 对应 的,当集合类被release的时候,它会发送对应的release消息给包含在其中的对象。 因此,如果你想建立一 个包含一堆number的数组,你可以像下面示例中的几个方法来做
NSMutableArray *array; int i;
for (i = 0; i < 10; i++) {
NSNumber *n = [NSNumber numberWithInt: i];
在这种情况下, 我们不需要retain这些number,因为array将替我们这么做。 NSMutableArray *array;
for (i = 0; i < 10; i++) {
NSNumber *n = [[NSNumber alloc] initWithInt: i];
在这个例子中,因为你使用了-alloc去建立了一个number,所以你必须显式的-release它,以保证retain count的平衡。因为将number加入数组的时候,已经retain它了,所以数组中的number变量不会被release
在实现UIView的动画的时候,并且使⽤用UIView来重复调⽤用它结束的回调时候要 注意以下⽅方法中的finished参数
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
if([finishied boolValue] == YES)
//一定要判断这句话,要不在程序中当多个View刷新的时候,就可能出现动画异常的现象 {
80、判断在UIViewController中,viewWillDisappear的时候是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
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");
NSString *string1 = @"abc / cde";
NSString *string2 = @"abc" @"cde";
NSString *string3 = @"abc" "cde";
NSLog( @"string1 is %@" , string1 );
NSLog( @"string2 is %@" , string2 ); NSLog( @"string3 is %@" , string3 );
string1 is abc cde string2 is abccde
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];
lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; //加粗并且倾斜
lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];
84、为IOS应用组件添加圆角的方法 具体的实现是使用QuartzCore库,下面我具体的描述一下实现过程:
• 首先创建一个项目,名字叫:ipad_webwiew
• 利⽤用Interface Builder添加⼀一个UIWebView,然后和相应的代码相关联 • 添加QuartzCore.framework
#import <QuartzCore/QuartzCore.h>
@interface ipad_webwiewViewController : UIViewController {
IBOutlet UIWebView *myWebView; UIView *myView;
@property (nonatomic,retain) UIWebView *myWebView; @end
[super viewDidLoad]; //给图层添加背景图⽚片: //myView.layer.contents = (id)[UIImage
imageNamed:@"view_BG.png"].CGImage; //将图层的边框设置为圆脚
myWebView.layer.cornerRadius = 8; myWebView.layer.masksToBounds = YES; //给图层添加⼀一个有⾊色边框
myWebView.layer.borderWidth = 5; myWebView.layer.borderColor = [[UIColor colorWithRed:0.52
green:0.09 blue:0.07 alpha:1] CGColor]; }
! [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 cancelPreviousPerformRequestsWithTarget: 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];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[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]; }
if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
[[UIApplication sharedApplication]
UIInterfaceOrientationLandscapeRight animated:NO];
转载地址:http://wrwpi.baihongyu.com/