iphone开发笔记和技巧总结
来源:互联网 发布:淘宝客微信群名称 编辑:程序博客网 时间:2024/06/06 18:01
//导入头文件
#import QuartzCore/QuartzCore.h
//将整个self.view大小的图层形式创建一张图片image
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];UIImage*image=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//然后将该图片保存到图片图
UIImageWriteToSavedPhotosAlbum(image,self,nil,nil);
1.颜色和字体
UIKit提供了UIColor和UIFont类来进行设置颜色和字体,
UIColor *redColor=【UIColor redColor】;
【redColor set】;//设置为红色
UIFont *front=【UIFont systemFontOfSize:14.0】;//获得系统字体
【myLable setFont:font】;//设置文本对象的字体
2.drawRect方法
对于画图,你首先需要重载drawRect方法,然后调用setNeedsDisplay方法让系统画图:
-(void)drawRect:(CGRect)rect;//在rect指定的区域画图
-(void)setNeedsDisplay;//让系统调用drawRect画图
延时函数和Timer的使用
延时函数:
[NSThread sleepForTimeInterval:5.0]; //暂停5s.
Timer的使用:
NSTimer *connectionTimer; //timer对象
//实例化timer
self.connectionTimer=[NSTimerscheduledTimerWithTimeInterval:1.5 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];
//用timer作为延时的一种方法
do{
[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
}while(!done);
//timer调用函数
-(void)timerFired:(NSTimer *)timer{
done =YES;
}
翻页效果
经常看到iPhone的软件向上向下翻页面的效果,其实这个很简单,已经有封装好的相关方法处理。
//首先设置动画的相关参数
[UIView beginAnimations:@"Curl"context:nil];
[UIView setAnimationDuration:1.25]; //时间
[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];//速度
//然后设置动画的动作和目标视图
[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
参数UIViewAnimationTransitionCurlUp代表向上翻页,如果向下的话UIViewAnimationTransitionCurlDown.
forView那把当前的视图传进去。
//最后提交动画
[UIView commitAnimations];
使用NSTimer与iphone的简单动画,实现飘雪效果
使用NSTimer与iphone的简单动画,实现飘雪效果,这理原理比较简单,就是定时生成一定的雪花图片,然后使用动画的方式向下漂落(我在其它论坛,看到使用path的方式实现的一个云漂来漂去的效果,实际也可以用那种方式实现,这实际就是前面说的动画效果的两种应用)。所以,我们可以在 viewDidLoad事件中,增加一个图片及定时器并启动,这里的pic请在头文件中定义。
-(void)viewDidLoad{
[super viewDidLoad];
self.pic = [UIImage imageNamed:@"snow.png"];//初始化图片
//启动定时器,实现飘雪效果
[NSTimer scheduledTimerWithTimeInterval:(0.2) target:self selector:@selector(ontime) userInfo:nil repeats:YES];
}
然后再实现定时器定时调用的ontime方法:
-(void)ontime{
UIImageView *view = [[UIImageView alloc] initWithImage:pic];//声明一个UIImageView对象,用来添加图片
view.alpha = 0.5;//设置该view的alpha为0.5,半透明的
int x = round(random()%320);//随机得到该图片的x坐标
int y = round(random()%320);//这个是该图片移动的最后坐标x轴的
int s = round(random()%15)+10;//这个是定义雪花图片的大小
int sp = 1/round(random()%100)+1;//这个是速度
view.frame = CGRectMake(x, -50, s, s);//雪花开始的大小和位置
[self.view addSubview:view];//添加该view
[UIView beginAnimations:nil context:view];//开始动画
[UIView setAnimationDuration:10*sp];//设定速度
view.frame = CGRectMake(y, 500, s, s);//设定该雪花最后的消失坐标
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}
使用NSTimer实现倒计时
今天在CocoaChina上面看到有人在问倒计时怎么做,记得以前在看Iphone31天的时候做过一个,今天翻出来运行不了了,原因是我的IphoneSDK升级到3.1了,以前使用的是2.2.1,在2.2.1里面是可以使用NSCalendarDate的,但是在3.1里面不能够使用,怎么办,只好用NSTimer了,最后还是给实现了。代码也比较简单,开始运行viewDidLoad的时候加载 [NSTimerscheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(timerFireMethod:) userInfo:nilrepeats:YES];//使用timer定时,每秒触发一次
,然后就是写selector了。
-(void)timerFireMethod:(NSTimer*)theTimer
{
//NSDateFormatter *dateformatter =[[[NSDateFormatter alloc]init]autorelease];//定义NSDateFormatter用来显示格式
//[dateformatter setDateFormat:@"yyyy MM dd hh mmss"];//设定格式
NSCalendar *cal = [NSCalendarcurrentCalendar];//定义一个NSCalendar对象
NSDateComponents *shibo = [[NSDateComponentsalloc] init];//初始化目标时间(好像是世博会的日期)
[shibo setYear:2010];
[shibo setMonth:5];
[shibo setDay:1];
[shibo setHour:8];
[shibo setMinute:0];
[shibo setSecond:0];
NSDate *todate = [caldateFromComponents:shibo];//把目标时间装载入date
[shibo release];
// NSString *ssss = [dateformatterstringFromDate:dd];
// NSLog([NSString stringWithFormat:@"shiboshi:%@",ssss]);
NSDate *today = [NSDate date];//得到当前时间
// NSString *sss = [dateformatterstringFromDate:today];
// NSLog([NSString stringWithFormat:@"xianzaishi:%@",sss]);
//用来得到具体的时差
unsigned int unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlagsfromDate:today toDate:todate options:0];
lab.text = [NSStringstringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day],[d hour], [d minute], [d second]];
}
这样就实现了倒计时的功能。
1。隐藏状态栏[[UIApplication sharedApplication] setStatusBarHidden:YES];
/******************************************************************************
1、取随机数:
NSData *datanow = [NSData data];
int i = (int)datanow;
srand(i);
rand();
//int effectPicNum = rand()%7;
******************************************************************************/
/******************************************************************************
2、播放音乐:
-(void) playMusic
{
@try{
//取文件路径
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"startLogo" ofType:@"mp3"];
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
musicPlayer= [[AVAudioPlayeralloc] initWithContentsOfURL:musicURL error:nil];
[musicURL release];
//[musicPlayer prepareToPlay];
//[musicPlayer setVolume:1]; //设置音量大小
musicPlayer.numberOfLoops= 0; //设置播放次数,-1为一直循环,0为一次
[musicPlayerplay];
}
@catch(NSException* e) {
}
}
******************************************************************************/
/******************************************************************************
3、每隔0.8秒执行timeCount方法:
NSTimer*countTimer;
countTimer= [NSTimerscheduledTimerWithTimeInterval: 0.8target: selfselector: @selector(timeCount:) userInfo: nilrepeats: YES];
[countTimerfire]; //执行timer
******************************************************************************/
/******************************************************************************
4、延迟1秒执行test方法:
[selfperformSelector:@selector(test) withObject:nilafterDelay:0.1];
******************************************************************************/
/******************************************************************************
5、启动线程:
[NSThreaddetachNewThreadSelector:@selector(transImage) toTarget:selfwithObject:nil];
timer=[NSTimerscheduledTimerWithTimeInterval:0.03target:selfselector:@selector(TimerClock:) userInfo:nilrepeats:YES]; //启动一个NSTimer执行广播
[timerfire]; //执行timer
-(void)TimerClock:(id)sender
{
//控制延迟触发
if(Timecontrol>1) {
[timerConditionbroadcast]; //广播,触发处于等待状态的timerCondition
}
}
-(void)transImage
{
isRunning=YES;
while (countTime < COUNTTIME) {
[timerConditionwait];
lim += 255 / (2 * KFrame);
[selfprocessImage];
countTime += 1000 / KFrame;
}
[timerinvalidate];
isRunning=NO;
}
******************************************************************************/
/******************************************************************************
6、获取文件路径:
//通过NSHomeDirectory获得文件路径
NSString *homeDirectory = NSHomeDirectory();
NSString *fileDirectory = [homeDirectory stringByAppendingPathComponent:@"temp/app_data.plist"];
//使用NSSearchPathForDirectoriesInDomains检索指定路径
NSArray*path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//常量NSDocumentDirectory表示正在查找Documents目录的路径(使用NSCachesDirectory表明要查找的时Caches文件夹),常量NSUserDomainMask表明我们希望将搜索限制于我们应用程序的沙盒,最后一个参数决定了是否“展开”波浪线符号。
//在Mac系统中,‘~’表示主路经(Home),如果不展开,路径看起来就是:‘~/Documents’,展开后即得到完整路径。这个参数一直设置位真即可。
NSString *documentsDirectory = [paths objectAtIndex:0];z
NSString *fileDirectory = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
//使用Foundation中的NSTemporaryDirectory函数直接返回代表temp文件夹的全路径的字符串对象
NSString *tempDirectory = NSTemporaryDirectory();
NSString*file = [tempDirectory stringByAppendingPathComponent:@"file.txt"];
Example:
NSArray*path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *docDir = [path objectAtIndex:0];
NSLog(@"filepath:%@",docDir);
NSString*str = @"hello.jpg";
NSString*filepath = [docDir stringByAppendingPathComponent:str];
//NSString *filepath = [docDir stringByAppendingPathComponent:[NSString stringWithUTF8String:"///mest.txt"]];
NSLog(@"filepath:%@",filepath);
BOOLsuccess = [[NSFileManagerdefaultManager]createFileAtPath: filepath contents:nilattributes:nil];
NSLog(@"result",success);
printf("Create File:%s %s.",[filepath UTF8String], success ? "Success": "Error");
NSString* reValue= [NSString stringWithString:@"\"success\""];
NSLog(reValue);
******************************************************************************/
/************************************************************************************************************************************************************
7文件、文件夹操作
//如果"/Documents/Theme"路径不存在,则创建。
if(![[NSFileManagerdefaultManager]fileExistsAtPath:themePath])
{
[[NSFileManagerdefaultManager] createDirectoryAtPath:themePath attributes:nil];
}
//删除已存在的同名文件夹
if([[NSFileManagerdefaultManager] fileExistsAtPath:savePath]) {
[[NSFileManagerdefaultManager] removeItemAtPath:savePath error:NULL];
}
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
7 子线程抛给主线程:
[selfperformSelectorOnMainThread:@selector(shiftView) withObject:nilwaitUntilDone:YES];
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
8获取当前时间
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
//获取当前时间作为productId
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"hhmmss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
downloadInfo.productId = locationString;
[formatter release];
/******************************************************************************
函数名称 : getDate
函数描述 : 获取当前日期时间
输入参数 : N/A
输出参数 : N/A
返回值 : NSString 当前时间
备注 :
******************************************************************************/
-(NSString *)getDate
{
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
[formatter release];
return locationString;
}
大写的H日期格式将默认为24小时制,小写的h日期格式将默认为12小时
不需要特别设置,只需要在dataFormat里设置类似"yyyy-MMM-dd"这样的格式就可以了
日期格式如下:
y 年 Year 1996; 96
M 年中的月份 Month July; Jul; 07
w 年中的周数 Number 27
W 月份中的周数 Number 2
D 年中的天数 Number 189
d 月份中的天数 Number 10
F 月份中的星期 Number 2
E 星期中的天数 Text Tuesday; Tue
a Am/pm 标记 Text PM
H 一天中的小时数(0-23) Number 0
k 一天中的小时数(1-24) Number 24
K am/pm 中的小时数(0-11) Number 0
h am/pm 中的小时数(1-12) Number 12
m 小时中的分钟数 Number 30
s 分钟中的秒数 Number 55
S 毫秒数 Number 978
z 时区 General time zone Pacific Standard Time; PST; GMT-08:00
Z 时区 RFC 822 time zone -0800
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
读取和写入plist文件
plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法: 以下代码在Mac和iPhone中均适用。
写入plist文件: NSMutableDictionary * dict = [ [ NSMutableDictionary alloc ] initWith
plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法:
以下代码在Mac和iPhone中均适用。
写入plist文件:
NSMutableDictionary* dict = [ [ NSMutableDictionaryalloc ] initWithContentsOfFile:@"/Sample.plist"];
[ dict setObject:@"Yes"forKey:@"RestartSpringBoard"];
[ dict writeToFile:@"/Sample.plist"atomically:YES];
读取plist文件:
NSMutableDictionary* dict = [ [ NSMutableDictionaryalloc ] initWithContentsOfFile:@"/Sample.plist"];
NSString* object = [ dict objectForKey:@"RestartSpringBoard" ];
************************************************************************************************************************************************************/
1. UIImageView上面添加按钮,按钮不响应点击时间怎么办?把UIImageVIew的userInteractionEnabled属性设置为YES啊。
2. 透明的UIView遮挡住了SuperView,使SuperView不能响应点击事件怎么办?把UIView的userInteractionEnabled属性设置为NO啊。
UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320, 44)];
imgView.userInteractionEnabled=YES;
UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:selfaction:@selector(onClickImage)];
[imgView addGestureRecognizer:singleTap];
[singleTap release];
-(void)onClickImage{
// here, do whatever you wantto do
NSLog(@"imageview is clicked!");
}
iphone调用系统电话、浏览器、地图、邮件等
openURL的使用方法:
view plaincopy toclipboardprint?
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appString]];
其中系统的appString有:
view plaincopy toclipboardprint?
1.Map http://maps.google.com/maps?q=Shanghai
2.Email mailto://myname@google.com
3.Tel tel://10086
4.Msg sms://10086
openURL能帮助你运行Maps,SMS,Browser,Phone甚至其他的应用程序。这是Iphone开发中我经常需要用到的一段代码,它仅仅只有一行而已。
- (IBAction)openMaps {
//打开地图
NSString*addressText = @"beijing";
//@"1Infinite Loop, Cupertino, CA 95014";
addressText =[addressTextstringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString*urlText = [NSStringstringWithFormat:@"http://maps.google.com/maps?q=%@",addressText];
NSLog(@"urlText=============== %@", urlText);
[[UIApplicationsharedApplication] openURL:[NSURL URLWithString:urlText]];
}
- (IBAction)openEmail {
//打开mail // Fire off an email to apple support
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"mailto://devprograms@apple.com"]];
}
- (IBAction)openPhone {
//拨打电话
// CallGoogle 411
[[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"tel://8004664411"]];
}
- (IBAction)openSms {
//打开短信
// Text toGoogle SMS
[[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"sms://466453"]];
}
-(IBAction)openBrowser {
//打开浏览器
// Lanuch any iPhone developers fav site
[[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"http://itunesconnect.apple.com"]];
}
键盘透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
状态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。
更改cell选中的背景
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;
- iPhone开发笔记和技巧总结
- iphone开发笔记和技巧总结
- iphone开发笔记和技巧总结
- iphone开发笔记和技巧总结
- iphone开发笔记和技巧总结
- iphone开发笔记和技巧总结
- iPhone开发笔记和技巧总结 (一)
- iphone 开发技巧总结
- ios学习--iphone开发笔记和技巧总结(原址持续更新)
- ios学习--iphone开发笔记和技巧总结(原址持续更新)
- iphone 开发技巧总结篇
- iPhone开发技巧笔记壹
- iOS 开发笔记和技巧总结(一)
- iOS 开发笔记和技巧总结 (二)
- iOS 开发笔记和技巧总结 (三)
- iOS 开发笔记和技巧总结 (四)
- iOS 开发笔记和技巧总结 (五)
- ios 开发笔记和技巧总结 (六)
- VMware虚拟机以NAT方式无法上网的问题
- 一步一步写算法(之排序二叉树删除-2)
- JS小功能点积累
- red5和java.exe端口冲突
- matlab 写txt文件
- iphone开发笔记和技巧总结
- Java小计
- C++深复制和浅复制
- flappy bird大集集
- C++ 没有小结的小结
- 一步一步写算法(之排序二叉树删除-3)
- 在IIS7中应用Application Request Routing配置反向代理
- 面试经典(16)--二叉树根节点到指定节点的路径
- 百度面试题d(n)