常用iPhone SDK代码示例
2011-10-24 14:09 Paul Wong 阅读(3768) 评论(1) 编辑 收藏 举报记录:
在Xcode,单击Run>Console查看NSLog语句。
NSLog(@"log: %f ", myFloat);
NSLog(@"log: %i ", myInt);
显示图片:
不使用UIBuilder,在屏幕任意处显示图片。你也能够看到其他类型的视图。
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; // explicitly opaque for performance
[self.view addSubview:myImage];
[myImage release];
web视图:
一个基本的UIWebView。
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
显示网络活动状态指示灯:
这是iphone左上角状态显示的网络状态图标。
app.networkActivityIndicatorVisible = YES; // to stop it, set this to NO
动画:序列图
显示一系列图片。
[UIImage imageNamed:@"myImage1.png"],
[UIImage imageNamed:@"myImage2.png"],
[UIImage imageNamed:@"myImage3.png"],
[UIImage imageNamed:@"myImage4.gif"],
nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages;
myAnimatedView.animationDuration = 0.25; // seconds
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];
动画:移动对象
显示在屏幕移动的东西,注:这种动画是“懒惰”的,你不能从这动画中获得任何对象(例如当前的位置),如果你需要这些信息,你需要用NSTimer手动控制其x,y坐标。
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];
字符串和整型:
下面用一个文本标签显示一个整型的值。
currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore];
可拖动的项:
这里介绍怎样创建一个可拖动的图片。
1.创建一个继承于UIImageView的类。
}
2.在实现文件中,增加两个方法。
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
3.现在你可以在任何新的图像中增加此功能了。
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];
振动与声音:
这里是如何使手机振动。
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
声音一般是可以在模拟器中模拟的,但有些声音是无法在模拟器中模拟或是需要特定的音频格式。
id sndpath = [[NSBundle mainBundle]
pathForResource:@"mySound"
ofType:@"wav"
inDirectory:@"/"];
CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath];
AudioServicesCreateSystemSoundID (baseURL, &pmph);
AudioServicesPlaySystemSound(pmph);
[baseURL release];
线程:
1.创建新线程。
toTarget:self
withObject:nil];
2.创建线程调用的方法。
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
如果你需要在主线程中做一些事情,你可以使用performSelectorOnMainThread.
withObject:nil
waitUntilDone:false];
在其他类中访问属性/方法:
其他一个方法是通过AppDelegate。
= (myAppDelegate *)[[UIApplication sharedApplication] delegate];
[[[appDelegate rootViewController] flipsideViewController] myMethod];
随机数:
可以使用arc4random(),random() ,但要手动实现,而应该首选arc4random()。
计时器:
计时器能够每隔一秒调用我们的方法。
target:self
selector:@selector(myMethod)
userInfo:nil
repeats:YES];
如果你想传递一个对象到myMethod,请使用userInfo属性。
1.首先创建一个Timer。
target:self
selector:@selector(myMethod)
userInfo:myObject
repeats:YES];
2.传递计时器对象到你的方法。
// Now I can access all the properties and methods of myObject
[[timer userInfo] myObjectMethod];
}
3.停止计时器用invalidate。
myTimer = nil; // ensures we never invalidate an already invalid Timer
时间:
用CFAbsoluteTimeGetCurrent()来获取时间。
// perform calculations here
提示:
显示一个带有OK按钮的提示框。
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!"
[alert show];
[alert release];
plist文件:
plist文件能够储存在程序程序中的资源文件夹,当应用程序首次启动时,会自动检测用户文件夹是否存在plist文件,如果没有,应该在应用程序包中复制一份。
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:plistName ofType:@"plist"];
}
现在从文档中读取plist文件。
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath
stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
现在读取并设置键值。
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];
信息按钮:
为了容易触摸,增加按钮的范围。
infoButton.frame.origin.y-25, infoButton.frame.size.width+50,
infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];
检测子视图:
你可以循环测试子视图,如果使用了标签属性,这是很好用的。
if (anImage.tag == 1) {
// do something
}
}
本文摘自:http://www.iphoneexamples.com/ ,感谢阅读,希望对您有用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?