美文网首页iOS Developer
ios常用知识点(转载)

ios常用知识点(转载)

作者: wzjmyff | 来源:发表于2017-02-09 13:35 被阅读41次

      转载自cocoaChina http://www.cocoachina.com/bbs/read.php?tid-73570.html    记录以备用

    iphone程序中实现截屏的一种方法

    在iphone程序中实现截屏的一种方法:

    //导入头文件

    #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开发实现splash画面非常简单,做一个全屏的欢迎页的图片,把它命名为Default.png,然后放在Xcode工程的Resource里面。

    在XXXAppDelegate.m程序中,插入如下代码:

    -(BOOL)application:(UIApplication*)application

    didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{

    //–inserta delay of 5 seconds before the splash screendisappears–

    [NSThread sleepForTimeInterval:5.0];

    //Override point for customization after applicationlaunch.

    //Add the view controller’s view to the window anddisplay.

    [windowaddSubview:viewController.view];

    [windowmakeKeyAndVisible];

    returnYES;

    }

    这样splash页面就停留5秒后,消失了。

    关于控制器Controller的思考

    iPhone开发中,只有一个窗口,对应的是多个视图,而视图的组织形式各种各样,关键是要靠控制器来组织各个视图的逻辑关系。大体的关系如下:

    窗体---主控制器(比如说导航控制器),主控制器在窗体里面,拖动过去即可,在AppDelegate中写相关变量的代码---在主控制器下有别的控制器,比如视图控制器,可以通过interfacebuilder来关联根视图什么的----视图控制器相当于一个根视图,可以调用其他的视图---视图中包含类文件(.h,.m)和图形界面文件(.xib)(两个之间必须关联起来。)

    翻页效果

    经常看到iPhone的软件向上向下翻页面的效果,其实这个很简单,已经有封装好的相关方法处理。

    //首先设置动画的相关参数

    [UIView beginAnimations:@"Curl"context:nil];

    [UIView setAnimationDuration:1.25];//时间

    [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];//速度

    //然后设置动画的动作和目标视图

    [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:self.viewcache:YES];

    参数UIViewAnimationTransitionCurlUp代表向上翻页,如果向下的话UIViewAnimationTransitionCurlDown.

    forView那把当前的视图传进去。

    //最后提交动画

    [UIView commitAnimations];

    截取屏幕图片

    //创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)

    UIGraphicsBeginImageContext(CGSizeMake(200,400));

    //renderInContext 呈现接受者及其子范围到指定的上下文

    [self.view.layerrenderInContext:UIGraphicsGetCurrentContext()];

    //返回一个基于当前图形上下文的图片

    UIImage *aImage =UIGraphicsGetImageFromCurrentImageContext();

    //移除栈顶的基于当前位图的图形上下文

    UIGraphicsEndImageContext();

    //以png格式返回指定图片的数据

    imageData = UIImagePNGRepresentation(aImage);

    使用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]];

    }

    这样就实现了倒计时的功能。

    Iphone幻灯片效果+背景音乐

    今天弄了几张好看的图片,我就摸索着实现了图片的幻灯片效果,这个以前也实现过了,也算是温故知新吧,另外就是使用SoundEngine类实现背景音乐的播放。SoundEngine类可以从[url=read.php?tid-1215.html]http://www.cocoachina.com/bbs/read.php?tid-1215.html[/url]下载到。

    代码很简单贴出来,以备不时只需:

    -(void)viewDidLoad

    {

    array = [[NSMutableArray alloc] init];

    int i = 1;

    for(i;i<=30;i++)

    {

    [array addObject:[UIImageimageNamed:[NSString stringWithFormat:@"%d.jpg",i]]];

    }

    pictures.animationImages = array;

    pictures.animationDuration = 300;//时间间隔

    pictures.animationRepeatCount = 0;//循环播放

    [pictures startAnimating];//开始播放

    //播放背景音乐,利用SoundEngine类进行播放

    SoundEngine_SetListenerPosition(0.0, 0.0,1.0);

    SoundEngine_Initialize(44100);

    SoundEngine_LoadBackgroundMusicTrack([[[NSBundlemainBundle] pathForResource:@"win" ofType:@"caf"] UTF8String],true, true);

    SoundEngine_StartBackgroundMusic();

    }

    NSTimer的用法

    iPhone为我们提供了一个很强大得时间定时器 NSTimer,它可以完成任何定时功能:

    我们使用起来也很简单,只要记住三要素就可以,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理delegate和事件处理方法@selector();

    就可以用

    1+(NSTimer*)scheduledTimerWithTimeIn

    2terval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;[/pre]来初始化一个 时间定时器

    下面我写了一个很简单得例子:

    -(void)initTimer

    {

    //时间间隔4NSTimeInterval timeInterval=1.0;

    //定时器6NSTimer   showTimer=[NSTimer scheduledTimerWithTimeInterval:maxShowTime

    target:self

    selector:@selector(handleMaxShowTimer:)

    userInfo:nil

    repeats:NO];

    }

    //触发事件13-(void)handleMaxShowTimer:(NSTimer*)theTimer

    {

    NSDateFormatter dateFormator=[[NSDateFormatter alloc] init];

    dateFormator.dateFormat=@"yyyy-MM-dd  HH:mm:ss";

    NSString*date=[dateformater stringFromDate:[NSDate date]];

    if([date isEqualToString:@"2010-11-09 23:59:59"])

    {

    UIAlertView*alert=[[UIAlertView alloc] initWithTitle:TITLE_NAME

    message:@"现在马上就有新的一天了!"22delegate:self

    cancelButtonTitle:nil

    otherButtonTitles:CONFIRM_TITLE, nil];

    [alert show];

    [alert release];

    }

    [data release];

    [dateFormator release];

    }

    iphone 学习笔记

    1。隐藏状态栏[[UIApplicationsharedApplication]setStatusBarHidden:YES];

    /******************************************************************************

    1、取随机数:

    NSData*datanow = [NSDatadata];

    inti = (int)datanow;

    srand(i);

    rand();

    //int effectPicNum = rand()%7;

    ******************************************************************************/

    /******************************************************************************

    2、播放音乐:

    -(void) playMusic

    {

    @try{

    //取文件路径

    NSString*musicFilePath = [[NSBundlemainBundle]pathForResource:@"startLogo"ofType:@"mp3"];

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

    musicPlayer= [[AVAudioPlayeralloc]initWithContentsOfURL:musicURLerror:nil];

    [musicURLrelease];

    //[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

    [timerConditionwait];

    lim+=255/ (2*KFrame);

    [selfprocessImage];

    countTime+=1000/KFrame;

    }

    [timerinvalidate];

    isRunning=NO;

    }

    ******************************************************************************/

    /******************************************************************************

    6、获取文件路径:

    //通过NSHomeDirectory获得文件路径

    NSString*homeDirectory =NSHomeDirectory();

    NSString*fileDirectory = [homeDirectorystringByAppendingPathComponent:@"temp/app_data.plist"];

    //使用NSSearchPathForDirectoriesInDomains检索指定路径

    NSArray*path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    //常量NSDocumentDirectory表示正在查找Documents目录的路径(使用NSCachesDirectory表明要查找的时Caches文件夹),常量NSUserDomainMask表明我们希望将搜索限制于我们应用程序的沙盒,最后一个参数决定了是否“展开”波浪线符号。

    //在Mac系统中,‘~’表示主路经(Home),如果不展开,路径看起来就是:‘~/Documents’,展开后即得到完整路径。这个参数一直设置位真即可。

    NSString*documentsDirectory = [pathsobjectAtIndex:0];z

    NSString*fileDirectory = [documentsDirectorystringByAppendingPathComponent:@"file.txt"];

    //使用Foundation中的NSTemporaryDirectory函数直接返回代表temp文件夹的全路径的字符串对象

    NSString*tempDirectory =NSTemporaryDirectory();

    NSString*file = [tempDirectorystringByAppendingPathComponent:@"file.txt"];

    Example:

    NSArray*path =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);

    NSString*docDir = [pathobjectAtIndex:0];

    NSLog(@"filepath:%@",docDir);

    NSString*str =@"hello.jpg";

    NSString*filepath = [docDirstringByAppendingPathComponent:str];

    //NSString *filepath = [docDir stringByAppendingPathComponent:[NSString stringWithUTF8String:"///mest.txt"]];

    NSLog(@"filepath:%@",filepath);

    BOOLsuccess = [[NSFileManagerdefaultManager]createFileAtPath: filepathcontents:nilattributes:nil];

    NSLog(@"result",success);

    printf("Create File:%s %s.",[filepathUTF8String], success ?"Success":"Error");

    NSString* reValue= [NSStringstringWithString:@"\"success\""];

    NSLog(reValue);

    ******************************************************************************/

    /************************************************************************************************************************************************************

    7文件、文件夹操作

    //如果"/Documents/Theme"路径不存在,则创建。

    if(![[NSFileManagerdefaultManager]fileExistsAtPath:themePath])

    {

    [[NSFileManagerdefaultManager]createDirectoryAtPath:themePathattributes:nil];

    }

    //删除已存在的同名文件夹

    if([[NSFileManagerdefaultManager]fileExistsAtPath:savePath]) {

    [[NSFileManagerdefaultManager]removeItemAtPath:savePatherror:NULL];

    }

    ************************************************************************************************************************************************************/

    /************************************************************************************************************************************************************

    7 子线程抛给主线程:

    [selfperformSelectorOnMainThread:@selector(shiftView)withObject:nilwaitUntilDone:YES];

    ************************************************************************************************************************************************************/

    /************************************************************************************************************************************************************

    8获取当前时间

    NSDateFormatter*formatter = [[NSDateFormatteralloc]init];

    [formattersetDateFormat:@"yyyy-MM-dd hh:mm:ss"];

    NSString*locationString=[formatterstringFromDate: [NSDatedate]];

    //获取当前时间作为productId

    NSDateFormatter*formatter = [[NSDateFormatteralloc]init];

    [formattersetDateFormat:@"hhmmss"];

    NSString*locationString=[formatterstringFromDate: [NSDatedate]];

    downloadInfo.productId = locationString;

    [formatterrelease];

    /******************************************************************************

    函数名称  : getDate

    函数描述  : 获取当前日期时间

    输入参数  : N/A

    输出参数  : N/A

    返回值    : NSString 当前时间

    备注     :

    ******************************************************************************/

    -(NSString*)getDate

    {

    NSDateFormatter*formatter = [[NSDateFormatteralloc]init];

    [formattersetDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"];

    NSString*locationString=[formatterstringFromDate: [NSDatedate]];

    [formatterrelease];

    returnlocationString;

    }

    大写的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 = [ [NSMutableDictionaryalloc ] initWith

    plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法:

    以下代码在Mac和iPhone中均适用。

    写入plist文件:

    NSMutableDictionary* dict = [ [NSMutableDictionaryalloc ]initWithContentsOfFile:@"/Sample.plist"];

    [ dictsetObject:@"Yes"forKey:@"RestartSpringBoard"];

    [ dictwriteToFile:@"/Sample.plist"atomically:YES];

    读取plist文件:

    NSMutableDictionary* dict =  [ [NSMutableDictionaryalloc ]initWithContentsOfFile:@"/Sample.plist"];

    NSString* object = [ dictobjectForKey:@"RestartSpringBoard"];

    ************************************************************************************************************************************************************/

    UIView翻转效果实现

    新建一个view-based模板工程,在ViewController文件中添加下面的代码,即可实现翻转效果;

    - (void)viewDidLoad {

    [super viewDidLoad];

    //需要翻转的视图

    UIView *parentView = [[UIView alloc] initWithFrame:CGRectMake(0, 150, 320, 200)];

    parentView.backgroundColor = [UIColor yellowColor];

    parentView.tag = 1000;

    [self.view addSubview:parentView];

    }

    //需要在h头文件声明下面的动作响应函数

    //在xib文件中添加一个button,其响应函数为下面的函数

    //运行程序后,点击button就看到翻转效果

    -(IBAction)ActionFanzhuan{

    //获取当前画图的设备上下文

    CGContextRef context = UIGraphicsGetCurrentContext();

    //开始准备动画

    [UIView beginAnimations:nil context:context];

    //设置动画曲线,翻译不准,见苹果官方文档

    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    //设置动画持续时间

    [UIView setAnimationDuration:1.0];

    //因为没给viewController类添加成员变量,所以用下面方法得到viewDidLoad添加的子视图

    UIView *parentView = [self.view viewWithTag:1000];

    //设置动画效果

    [UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView:parentView cache:YES];  //从上向下

    // [UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:parentView cache:YES];   //从下向上

    // [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:parentView cache:YES];  //从左向右

    // [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:parentView cache:YES];//从右向左

    //设置动画委托

    [UIView setAnimationDelegate:self];

    //当动画执行结束,执行animationFinished方法

    [UIView setAnimationDidStopSelector:@selector(animationFinished:)];

    //提交动画

    [UIView commitAnimations];

    }

    //动画效果执行完毕

    - (void) animationFinished: (id) sender{

    NSLog(@"animationFinished !");

    }

    运行程序,点击按钮,就能看到动画效果了。

    [ 此帖被haoxue在2012-02-25 22:01重新编辑 ]

    回复引用分享

    举报顶端

    haoxue

    痛定思痛,人要知耻而后勇!

    级别: 精灵王

    状态:未签到- [2天]

    UID:39045

    精华:0

    发帖:1386

    可可豆:12975 CB

    威望:12975 点

    在线时间:827(时)

    注册时间:2010-11-21

    最后登录:2016-08-30

    26 楼:发表于:2011-09-17 11:40发自:Web Page

    只看该作者

    iPhone 实现动画效果

    iPhone中实现动画,主要有两种方式:UIView的动画块和Core Animation的CATransition类。

    1、UIView的动画块

    之所以称为动画块,是因为UView动画是成块运行的,也就是说作为完整的事务一次性运行。

    beginAnimation:context:标志动画块开始;

    commitAnimations标志动画块结束。(这个commit多少已经暗示这个操作是事务性的)

    这里面通常涉及4个操作:

    beginAnimation:context:标志动画块开始

    setAnimationCurve:定义动画加速或减速的方式,有四种,ease-in/ease-out,ease-in,linear,ease-out

    setAnimationDuration:定义动画持续时间(以秒为单位)

    commitAnimations:标志动画块结束

    所有这些操作都是针对UIView的,或者说是UIView的类函数。

    给段代码示例:

    1. CGContextRef context = UIGraphicsGetCurrentContext();

    [UIView beginAnimations:nil context:context];

    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    [UIView setAnimationDuration:2.0f];

    [UIView setAnimationBeginsFromCurrentState:YES];

    [UIView setAnimationDelegate:self];

    [UIView setAnimationDidStopSelector:@selector(animationFinished:)];

    [self.imageView setTransform:CGAffineTransformMakeScale(0.25f, 0.25f)];

    [UIView commitAnimations];

    (这里面设置了动画的delegate,在动画结束后执行animationFinished:函数)

    UIView除了实现上面这种简单的动画,还支持视图的翻转。例如在上面代码的[UIView commitAnimations]前加上下面这句,便可以实现视图的翻转(翻转后的试图中,imageView的大小变为原来的0.25倍):

    [UIViewsetAnimationTransition:UIViewAnimationTransitionFlipFromLeftforView:self.viewcache:YES];

    其中,参数UIViewAnimationTransitionFlipFromLeft定义了翻转的方式。

    iphone调用系统电话、浏览器、地图、邮件等

    openURL的使用方法:

    view plaincopy toclipboardprint?

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appString]];

    其中系统的appString有:

    view plaincopy toclipboardprint?

    1.Maphttp://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"]];

    }

    UIPageControl实现自定义按钮

    有时候UIPageControl需要用到白色的背景,那么会导致上面的点按钮看不见或不清楚,

    我们可以通过继承该类重写函数来更换点按钮的图片现实.

    实现思路如下.

    新建类继承UIPageControl :

    @interface MyPageControl : UIPageControl

    {

    UIImage*imagePageStateNormal;

    UIImage*imagePageStateHighlighted;

    }

    - (id)initWithFrame:(CGRect)frame;

    @property (nonatomic, retain) UIImage*imagePageStateNormal;

    @property (nonatomic, retain) UIImage*imagePageStateHighlighted;

    @end

    声明了初始化该类的函数

    用了两个UIImage保存两张图片,大家知道的, UIPageCotrol的按钮分为两态,一个是正常,一个是高亮

    接下来实现该类以及重写父类方法:

    @interfaceMyPageControl(private)  //声明一个私有方法,该方法不允许对象直接使用

    - (void)updateDots;

    @end

    @implementation MyPageControl  //实现部分

    @synthesize imagePageStateNormal;

    @synthesize imagePageStateHighlighted;

    - (id)initWithFrame:(CGRect)frame { //初始化

    self = [superinitWithFrame:frame];

    return self;

    }

    - (void)setImagePageStateNormal:(UIImage*)image {  //设置正常状态点按钮的图片

    [imagePageStateNormalrelease];

    imagePageStateNormal= [image retain];

    [self updateDots];

    }

    -(void)setImagePageStateHighlighted:(UIImage *)image { //设置高亮状态点按钮图片

    [imagePageStateHighlightedrelease];

    imagePageStateHighlighted= [image retain];

    [self updateDots];

    }

    - (void)endTrackingWithTouch:(UITouch*)touch withEvent:(UIEvent *)event { //点击事件

    [superendTrackingWithTouch:touch withEvent:event];

    [self updateDots];

    }

    - (void)updateDots { //更新显示所有的点按钮

    if(imagePageStateNormal || imagePageStateHighlighted)

    {

    NSArray*subview = self.subviews;  //获取所有子视图

    for(NSInteger i = 0; i < [subview count]; i++)

    {

    UIImageView*dot = [subview objectAtIndex:i];  //以下不解释,看了基本明白

    dot.image= self.currentPage == i ? imagePageStateNormal : imagePageStateHighlighted;

    }

    }

    }

    - (void)dealloc { //释放内存

    [imagePageStateNormalrelease], imagePageStateNormal = nil;

    [imagePageStateHighlightedrelease], imagePageStateHighlighted = nil;

    [super dealloc];

    }

    @end

    OK,在添加处加入以下来实例化该对象代码:

    MyPageControl *pageControl =[[MyPageControl alloc] initWithFrame:CGRectMake(0,0, 200, 30)];

    pageControl.backgroundColor = [UIColorclearColor];

    pageControl.numberOfPages = 5;

    pageControl.currentPage = 0;

    [pageControlsetImagePageStateNormal:[UIImageimageNamed:@"pageControlStateNormal.png"]];

    [pageControl setImagePageStateHighlighted:[UIImageimageNamed:@"pageControlStateHighlighted.png"]];

    [self.view addSubview:pageControl];

    [pageControl release];

    iPhone电子书toolbar的实现

    iPhone电子书的toolbar一般都设计成半透明,上面放置一个进度条和一个Label(用于显示页码),这里用代码做一个最基本的实现。

    生成一个UIToolbar

    UIToolbar*toolbar =[[[UIToolbaralloc]init]autorelease];

    toolbar.barStyle=UIBarStyleBlackTranslucent;

    [toolbarsizeToFit];

    CGFloattoolbarHeight =[toolbarframe].size.height;

    CGRectrootViewBounds =self.parentViewController.view.bounds;

    CGFloatrootViewHeight =CGRectGetHeight(rootViewBounds);

    CGFloatrootViewWidth =CGRectGetWidth(rootViewBounds);

    CGRectrectArea =CGRectMake(0, rootViewHeight-toolbarHeight,rootViewWidth, toolbarHeight);

    [toolbarsetFrame:rectArea];

    toolbar.backgroundColor= [UIColorclearColor];

    生成一个Slider

    UISlider*readSlider=[[[UISlideralloc]initWithFrame:CGRectMake(0,0,225,30)]autorelease];

    readSlider.minimumValue=0.0f;

    readSlider.maximumValue=1.0f;

    readSlider.continuous=YES;

    readSlider.enabled=YES;

    生成一个Label

    UILabel*readLabel=[[[UILabelalloc]initWithFrame:CGRectMake(230,0,50,30)]autorelease];

    readLabel.backgroundColor= [UIColorclearColor];

    readLabel.textColor=[UIColorwhiteColor];

    Slider和Label加入到toolbar中

    NSMutableArray*tbitems =[NSMutableArrayarray];

    [tbitemsaddObject:[[[UIBarButtonItem alloc]initWithCustomView:readSlider] autorelease]];

    [tbitemsaddObject:[[[UIBarButtonItemalloc] initWithCustomView:readLabel]autorelease]];

    toolbar.items= tbitems;

    toolbar加入到当前view中

    [self.navigationController.viewaddSubview:toolbar];

    点击屏幕即隐藏的功能,将toolbar的hidden属性置为YES即可

    toolBar.hidden=YES;

    iphone界面如何实现下拉列表

    代码如下:

    #import

    @interfaceDropDownList : UIView {

    UITextField* textField;//文本输入框

    NSArray* list;//下拉列表数据

    BOOLshowList;//是否弹出下拉列表

    UITableView* listView;//下拉列表

    CGRect oldFrame,newFrame;//整个控件(包括下拉前和下拉后)的矩形

    UIColor *lineColor,*listBgColor;//下拉框的边框色、背景色

    CGFloat lineWidth;//下拉框边框粗细

    UITextBorderStyle borderStyle;//文本框边框style

    }

    @property(nonatomic,retain)UITextField *textField;

    @property(nonatomic,retain)NSArray* list;

    @property(nonatomic,retain)UITableView* listView;

    @property(nonatomic,retain)UIColor *lineColor,*listBgColor;

    @property(nonatomic,assign)UITextBorderStyle borderStyle;

    -(void)drawView;

    -(void)setShowList:(BOOL)b;

    @end

    #import"DropDownList.h"

    @implementationDropDownList

    @synthesizetextField,list,listView,lineColor,listBgColor,borderStyle;

    - (id)initWithFrame:(CGRect)frame {

    if(self=[superinitWithFrame:frame]){

    //默认的下拉列表中的数据

    list=[[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",nil];

    borderStyle=UITextBorderStyleRoundedRect;

    showList=NO;//默认不显示下拉框

    oldFrame=frame;//未下拉时控件初始大小

    //当下拉框显示时,计算出控件的大小。

    newFrame=CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height*5);

    lineColor=[UIColor lightGrayColor];//默认列表边框线为灰色

    listBgColor=[UIColor whiteColor];//默认列表框背景色为白色

    lineWidth=1;//默认列表边框粗细为1

    //把背景色设置为透明色,否则会有一个黑色的边

    self.backgroundColor=[UIColor clearColor];

    [selfdrawView];//调用方法,绘制控件

    }

    returnself;

    }

    -(void)drawView{

    //文本框

    textField=[[UITextField alloc]

    initWithFrame:CGRectMake(0,0,

    oldFrame.size.width,

    oldFrame.size.height)];

    textField.borderStyle=borderStyle;//设置文本框的边框风格

    [selfaddSubview:textField];

    [textField addTarget:selfaction:@selector(dropdown) forControlEvents:UIControlEventAllTouchEvents];

    //下拉列表

    listView=[[UITableView alloc]initWithFrame:

    CGRectMake(lineWidth,oldFrame.size.height+lineWidth,

    oldFrame.size.width-lineWidth*2,

    oldFrame.size.height*4-lineWidth*2)];

    listView.dataSource=self;

    listView.delegate=self;

    listView.backgroundColor=listBgColor;

    listView.separatorColor=lineColor;

    listView.hidden=!showList;//一开始listView是隐藏的,此后根据showList的值显示或隐藏

    [selfaddSubview:listView];

    [listView release];

    }

    -(void)dropdown{

    [textField resignFirstResponder];

    if(showList) {//如果下拉框已显示,什么都不做

    return;

    }else{//如果下拉框尚未显示,则进行显示

    //把dropdownList放到前面,防止下拉框被别的控件遮住

    [self.superview bringSubviewToFront:self];

    [selfsetShowList:YES];//显示下拉框

    }

    }

    #pragma mark listViewdataSource method and delegate method

    -(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{

    returnlist.count;

    }

    -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    staticNSString *cellid=@"listviewid";

    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:cellid];

    if(cell==nil){

    cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault

    reuseIdentifier:cellid]autorelease];

    }

    //文本标签

    cell.textLabel.text=(NSString*)[list objectAtIndex:indexPath.row];

    cell.textLabel.font=textField.font;

    cell.selectionStyle=UITableViewCellSelectionStyleGray;

    returncell;

    }

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    returnoldFrame.size.height;

    }

    //当选择下拉列表中的一行时,设置文本框中的值,隐藏下拉列表

    -(void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    //NSLog(@"select");

    textField.text=(NSString*)[list objectAtIndex:indexPath.row];

    //NSLog(@"textField.text=%@",textField.text);

    [selfsetShowList:NO];

    }

    -(BOOL)showList{//setShowList:No为隐藏,setShowList:Yes为显示

    returnshowList;

    }

    -(void)setShowList:(BOOL)b{

    showList=b;

    NSLog(@"showlist is set ");

    if(showList){

    self.frame=newFrame;

    }else{

    self.frame=oldFrame;

    }

    listView.hidden=!b;

    }

    /*

    // Only override drawRect: if you perform custom drawing.

    // An empty implementation adversely affects performance during animation.

    - (void)drawRect:(CGRect)rect {

    // Drawing code.

    }

    */

    - (void)dealloc {

    [superdealloc];

    }

    @end

    iphone之UISegmentedControl

    代码:

    //选择按钮

    NSArray*buttonNames = [NSArray arrayWithObjects:@"今天", @"本周", @"本月",nil];

    UISegmentedControl* segmentedControl = [[UISegmentedControl alloc]initWithItems:buttonNames];

    [segmentedControl setFrame:CGRectMake(60, 10, 200, 40)];

    segmentedControl.selectedSegmentIndex=1;

    //添加事件

    [segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];

    [self.viewaddSubview:segmentedControl];

    [segmentedControl release];

    //事件

    -(void)segmentAction:(UISegmentedControl *)Seg{

    NSIntegerIndex = Seg.selectedSegmentIndex;

    NSLog(@"Seg.selectedSegmentIndex:%d",Index);

    }

    相关文章

      网友评论

        本文标题:ios常用知识点(转载)

        本文链接:https://www.haomeiwen.com/subject/wxeiittx.html