ios開發筆記


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);

Objective-C 畫圖
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
didFinishLaunchingWithOp
tions:(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];
 
 return YES;
}

這樣splash頁面就停留5秒后,消失了。
關於控制器Controller的思考
iPhone開發中,只有一個窗口,對應的是多個視圖,而視圖的組織形式各種各樣,關鍵是要靠控制器來組織各個視圖的邏輯關系。大體的關系如下:
窗體---主控制器(比如說導航控制器),主控制器在窗體里面,拖動過去即可,在AppDelegate中寫相關變量的代碼---在主控制器下有別的控制器,比如視圖控制器,可以通過interfacebuilder來關聯根視圖什么的----視圖控制器相當於一個根視圖,可以調用其他的視圖---視圖中包含類文件(.h,.m)和圖形界面文件(.xib)(兩個之間必須關聯起來。)
翻頁效果
經常看到iPhone的軟件向上向下翻頁面的效果,其實這個很簡單,已經有封裝好的相關方法處理。
//首先設置動畫的相關參數
[UIView beginAnimations:@"Curl"context:nil];
[UIView setAnimationDuration:1.25]; //時間
[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];//速度
//然后設置動畫的動作和目標視圖
[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
參數UIViewAnimationTransitionCurlUp代表向上翻頁,如果向下的話UIViewAnimationTransitionCurlDown.
forView那把當前的視圖傳進去。
//最后提交動畫
[UIView commitAnimations];

自定義按鈕
UIButton *Btn;
CGRect frame;       
 Btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; //按鈕的類型    
    [Btn setImage:[UIImage imageNamed:@“aaa.png”] forState:UIControlStateNormal];//設置按鈕圖片  
  Btn.tag = 10; 
   frame.size.width = 59;  //設置按鈕的寬度  
  frame.size.height = 59;   //設置按鈕的高度      
  frame.origin.x =150;   //設置按鈕的位置     
   frame.origin.y =260;       
 [Btn setFrame:frame];     
   [Btn setBackgroundColor:[UIColor clearColor]];      
    [Btn addTarget:self action:@selector(btnPressed:)forControlEvents:UIControlEventTouchUpInside];   //按鈕的單擊事件     
   [self.view addSubview:Btn];      
    [Btn release];
-(void)btnPressed:(id)sender {
    //在這里實現按鈕的單擊事件
}

截取屏幕圖片
//創建一個基於位圖的圖形上下文並指定大小為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();
}

用這種方法播放好像挺占用資源的,比較卡,以后再研究研究其它的方法。


















圖片:60b45f23g7555941505a5&690.png 
NSTimer的用法
iPhone為我們提供了一個很強大得時間定時器 NSTimer,它可以完成任何定時功能:
我們使用起來也很簡單,只要記住三要素就可以,具體得三要素是:時間間隔NSTimeInterval浮點型,事件代理delegate和事件處理方法@selector();

就可以用
1 +(NSTimer *)scheduledTimerWithTimeIn
2 terval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 
[/pre] 來初始化一個 時間定時器
下面我寫了一個很簡單得例子:
-(void)initTimer
 {
//時間間隔4 NSTimeInterval timeInterval =1.0;
 //定時器6 NSTimer   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:@"現在馬上就有新的一天了!"22 delegate:self
 cancelButtonTitle:nil
 otherButtonTitles:CONFIRM_TITLE, nil];
 [alert show];
[alert release];
}
[data release];
 [dateFormator release];
 }
iphone開發之 - 啟動頁面設置
         不管是開發個人項目還是公司項目,大家通常都有一個需求,就是,在app啟動的時候,指定一定的時間來顯示自己的或者公司的logo,那么,我就將剛剛寫好的啟動加載頁面設置代碼貢獻出來。(不對指出請留言,好的話也給我留個言吧,鼓勵下我!呵呵)
        這里我需要用到NSTimer這個東西,相關的內容可以查看API,有比較詳細的解釋。
          新建一個項目,隨便是什么項目,我建立的是“view based application”,然后,命名為“Logo”,然后確定。
          直接編輯“Resources"目錄下的"LogoViewController.xib”。將背景顏色改稱綠色,主要是為了當從logo頁跳轉過來的時候能有感覺到變化。
          然后新建一個NSTimer.

logoviewcon*lo = [[logoviewconallocinitWithNibName:@"logoviewcon"bundle:nil];
self.logo = lo;
[lo release];
[windowaddSubview:self.logo.view];
//初始化timmer
NSTimer*timer =  [NSTimerscheduledTimerWithTimeInterval1.5targetselfselector@selector(logo:) userInfonilrepeatsYES];
注意,初始化的代碼有這么一段:@selector(logo:),其的方法就是當這個1.5秒時間過去之后自動調用的方法
-(void) logo:(NSTimer*)timer{
[logo.view removeFromSuperview];
[timer invalidate];//這句代碼用來終止timmer,否則,每過1.5秒,就會執行該方法一次,我們是要在開始的時候執行一次就夠了。
}
iphone 學習筆記

1。隱藏狀態欄[[UIApplication sharedApplicationsetStatusBarHidden:YES];

/******************************************************************************
1、取隨機數:
NSData *datanow = [NSData data];       
int i = (int)datanow;               
srand(i);                              
rand();
//int effectPicNum = rand()%7;
******************************************************************************/
/******************************************************************************
2、播放音樂:
-(void) playMusic
{
@try{
//取文件路徑
NSString *musicFilePath = [[NSBundle mainBundlepathForResource:@"startLogo" ofType:@"mp3"];       
NSURL *musicURL = [[NSURL allocinitFileURLWithPath:musicFilePath];  
musicPlayer= [[AVAudioPlayerallocinitWithContentsOfURL:musicURL error:nil];
[musicURL release];
//[musicPlayer prepareToPlay];
//[musicPlayer setVolume:1];            //設置音量大小
musicPlayer.numberOfLoops0//設置播放次數,-1為一直循環,0為一次
[musicPlayerplay]; 
}
@catch(NSException* e) {
}

******************************************************************************/
/******************************************************************************
3、每隔0.8秒執行timeCount方法
NSTimer*countTimer;
countTimer= [NSTimerscheduledTimerWithTimeInterval0.8targetselfselector@selector(timeCount:)  userInfonilrepeatsYES];   
[countTimerfire];     //執行timer
******************************************************************************/
/******************************************************************************
4、延遲1秒執行test方法:
[selfperformSelector:@selector(testwithObject:nilafterDelay:0.1];
******************************************************************************/
/******************************************************************************
5、啟動線程:
[NSThreaddetachNewThreadSelector:@selector(transImagetoTarget: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(NSDocumentDirectoryNSUserDomainMaskYES);
//常量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(NSCachesDirectoryNSUserDomainMask,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])
{
[[NSFileManagerdefaultManagercreateDirectoryAtPath:themePath attributes:nil];
}
//刪除已存在的同名文件夾
if([[NSFileManagerdefaultManagerfileExistsAtPath:savePath]) {
[[NSFileManagerdefaultManagerremoveItemAtPath:savePath error:NULL];
}
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
7 子線程拋給主線程:
[selfperformSelectorOnMainThread:@selector(shiftViewwithObject:nilwaitUntilDone:YES];

************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
8獲取當前時間
NSDateFormatter*formatter = [[NSDateFormatterallocinit];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];

//獲取當前時間作為productId
NSDateFormatter*formatter = [[NSDateFormatterallocinit];
[formatter setDateFormat:@"hhmmss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
downloadInfo.productId = locationString;
[formatter release];
/******************************************************************************
 函數名稱  : getDate
函數描述  : 獲取當前日期時間
 輸入參數  : N/A
 輸出參數  : N/A
 返回值    : NSString 當前時間
 備注     :
 ******************************************************************************/
-(NSString *)getDate
{
NSDateFormatter*formatter = [[NSDateFormatterallocinit];
[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" ];
************************************************************************************************************************************************************/
 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 !");
}

運行程序,點擊按鈕,就能看到動畫效果了
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倍):

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
其中,參數UIViewAnimationTransitionFlipFromLeft定義了翻轉的方式。
關於UIView的userInteractionEnabled屬性
如果父視圖為ParentView包含一個Button,如果再ParentView上添加子視圖ChildView,且ChildView蓋住了Button,
那么Button就得到不響應了,為了讓Button響應,可以設置ChildView的userInteractionEnabled = NO;
最近被這個問題困擾了很久,開始想用事件傳遞的方法,重寫類繼承自UIView,最后被這簡單屬性搞定了....
讓一個UIImageView響應點擊事件
UIImageView *imgView =[[UIImageView allocinitWithFrame:CGRectMake(00,32044)];
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"]];
 }
iphone程序內調用谷歌地圖

使用CLLocationManager類,MKMapView並且實現<MKMapViewDelegate,CLLocationManagerDelegate>
//初始化CLLocationManager,CLLocationManager獲得當前地理坐標
locmanager=[[CLLocationManager alloc]init];

[locmanager setDelegate:self];
 //設置精確度
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];

[locmanagerstartUpdatingLocation];
執行完以后,會自動調用代理方法:

在代理方法:


- (void)locationManager:(CLLocationManager *)managerdidUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation *)oldLocation{
//初始化矩形大小
 CGRect rect=CGRectMake(0,0,320,460);
//設置地圖大小為矩形大小
map=[[MKMapView alloc] initWithFrame:rect];

CLLocationCoordinate2Dloc=[newLocation coordinate];
lat=loc.latitude;
lon=loc.longitude;

//coordinate坐標
CLLocationCoordinate2DtheCoordinate;
CLLocationCoordinate2DtheCenter;

//theCoordinate.latitude=lat;
//theCoordinate.longitude=lon;
theCoordinate=loc;
[map setDelegate:self];
//設置地圖顯示的類型,有衛星地圖,道路,等
[map setMapType:MKMapTypeStandard];
//[mapsetMapType:MKMapTypeSatellite];
//區域坐標Region(區域,地域)

MKCoordinateRegiontheRegin;
//theCenter.latitude=lat;
//theCenter.longitude=lon;
theCenter=loc;
theRegin.center=theCenter;

//坐標間距(span:間隔,間距)
MKCoordinateSpantheSpan;

theSpan.latitudeDelta=0.1;
theSpan.longitudeDelta=0.1;
//設置地圖顯示的區域,
theRegin.span=theSpan;
//[mapsetRegion:theRegin];
[map regionThatFits:theRegin];
map.showsUserLocation=YES;
[self.viewaddSubview:map];

}


- (MKAnnotationView *)mapView:(MKMapView *)mapViewviewForAnnotation:(id<MKAnnotation>)annotation{
NSLog(@"-------viewForAnnotation-------");
//此類可以顯示針一樣的圖標
MKPinAnnotationView*newAnnotation=[[MKPinAnnotationViewalloc] initWithAnnotation:annotationreuseIdentifier:@"annotation1"];

//newAnnotation.animatesDrop=YES;
//newAnnotation.animatesDrop=NO;

newAnnotation.pinColor=MKPinAnnotationColorPurple;
//顯示標志提示
newAnnotation.canShowCallout=YES;
return newAnnotation;
}
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 =[[[UIToolbar allocinitautorelease];
toolbar.barStyle=UIBarStyleBlackTranslucent;
[toolbar sizeToFit];
CGFloat toolbarHeight =[toolbar frame].size.height;
CGRect rootViewBounds =self.parentViewController.view.bounds;
CGFloat rootViewHeight =CGRectGetHeight(rootViewBounds);
CGFloat rootViewWidth =CGRectGetWidth(rootViewBounds);
CGRect rectArea = CGRectMake(0, rootViewHeight-toolbarHeight,rootViewWidth, toolbarHeight);
[toolbar setFrame:rectArea];
toolbar.backgroundColor= [UIColor clearColor];
生成一個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 = [UIColor clearColor];
readLabel.textColor =[UIColor whiteColor];
Slider和Label加入到toolbar中

NSMutableArray *tbitems =[NSMutableArray array];
[tbitems addObject:[[[UIBarButtonItem alloc]initWithCustomView:readSlider] autorelease]];
[tbitems addObject:[[[UIBarButtonItemalloc] initWithCustomView:readLabel]autorelease]]; 
toolbar.items = tbitems;
toolbar加入到當前view中 
[self.navigationController.view addSubview:toolbar];
點擊屏幕即隱藏的功能,將toolbar的hidden屬性置為YES即可

toolBar.hidden = YES;
 
UIView中bounds和frame的差別?
翻譯文檔上的
bounds是指這個view在它自己坐標系的坐標和大小 而frame指的是這個view在它superview的坐標系的坐標和大小
區別主要在坐標系這一塊。

很明顯一個是自己為原點的坐標系,一個是以屏幕為原點的坐標系。絕對坐標。。。相對坐標。。。比如屏幕旋轉的時候就要以相對來重繪。 

frame 如果一個按鈕,是在表格里,按鈕的frame 的坐標也是相對的,並不是相對屏幕,也就是說是相對坐標,不是絕對坐標

我也想知道任何一個uiview如何求得它在屏幕上的坐標。

view 的frame是view在它的super view 的位置與尺寸。
view 的bounds可以用來幫助它的subview來定位的 ,layoutSubviews。


Frame  is  in  terms  of  superview's  coordinate  system   

框架是從父視圖的坐標系統


Bounds   is  in  terms  of   local  coordinate  system
是在局部坐標系統

[ 此帖被haoxue在2011-11-26 16:07重新編輯 ]
圖片:6_491_772cfea14e61028.png 
很明顯,bounds的原點是(0,0)點,而frame的原點卻是任意的。
frame 如果一個按鈕,是在表格里,按鈕的frame 的坐標也是相對的,並不是相對屏幕,也就是說是相對坐標,不是絕對坐標。
frame 是相對坐標。 bounds 是絕對坐標。
Android的開發過程中, 絕對坐標,這樣畫出來的位置都是相對於屏幕的而不是相對於控件的

 什么是絕對坐標值,相對坐標值?
絕對坐標是:X,Y    就是相對於坐標原點的。                    
例如(15,20)相對坐標是:@X,Y   就是相對於參考點(可以是自己設定的一個點)。                  
   例如(15,20)相對於參考點(1,1)的坐標,表示:@14,19                            
(15,20)相對於參考點(-1,-1)的坐標,表示:@16,21

bounds是指這個view在它自己坐標系的坐標和大小 而frame指的是這個view在它superview的坐標系的坐標和大小.
區別主要在坐標系這一塊。
很明顯一個是自己為原點的坐標系,一個是以屏幕為原點的坐標系。

[ 此帖被haoxue在2011-11-26 16:12重新編輯 ]
圖片:frame_bounds_rects.jpg 
多使用宏定義常量。tag,frame大小,一些判斷標志位。
#define kIndexValueTag 1

蘋果屏幕截圖快捷鍵

一般在Mac上用Command-Shif-3/4來截圖。注:Command=蘋果鍵 其實還有幾個輔助鍵,來起到不同的截圖功能……
01 1)Command-Shift-3(適用於OS9,10.1X和10.2)

02 將整個屏幕拍下並保存到桌面。

03 2)Command-Shift-4(適用於OS9,10.1X和10.2)

04 將屏幕的一部分拍下並保存到桌面。當按下着幾個鍵后,光標會變為一個十字,可以拖拉來選取拍報區域。

05 3)Command-Shift-Control-3(適用於OS9和10.2)

06 將整個屏幕拍下並保存到剪貼板,可以Command+V直接粘貼到如Photoshop等軟件中編輯。

07 4)Command-Shift-Control-4(適用於OS9和10.2)

08 將屏幕的一部分拍下並保存到剪貼板。

09 5)Command-Shift-4再按空格鍵(適用於10.2)

10 光標會變成一個照相機,點擊可拍下當前窗口或菜單或Dock以及圖標等,只要將照相機移動到不用區域(有效區域會顯示為淺藍色)點擊。

11 6)Command-Shift-Control-4再按空格鍵(適用於10.2)

12 將選取的窗口或其他區域的快照保存到剪貼板。

13 7)Command-Shift-Capslock-4(適用於OS9)

14 將當前的窗口拍下並保存到桌面。

15 8)Command-Shift-Capslock-Control-4(適用於OS9)

16 將當前的窗口拍下並保存到剪貼板。
設置透明度



1 [myView setAlpha:value];   (0.0 < value < 1.0)



設置背景色
1 [myView setBackgroundColor:[UIColor redColor]];

2 (blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;

3 orangeColor;purpleColor;brownColor; clearColor; )



自定義顏色:
1 UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)];      0.0~1.0



寬度和高度
1 768X1024     1024X768    狀態欄高 20 像素高   導航欄 工具欄 44像素高



隱藏狀態欄:
1 [[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]
iOS開發_iphone開發_iphone界面如何實現下拉列表


    
代碼如下:
     
     #import  <UIKit/UIKit.h>
     @interface  DropDownList : UIView<UITableViewDelegate,UITableViewDataSource> {
    UITextField* textField;    // 文本輸入框
    NSArray* list;             // 下拉列表數據
     BOOL  showList;              // 是否彈出下拉列表
    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"
    @implementation  DropDownList
     @synthesize  textField,list,listView,lineColor,listBgColor,borderStyle;
    - ( id )initWithFrame:(CGRect)frame {
     
     if ( self =[ super  initWithFrame: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];
    [ self  drawView]; // 調用方法,繪制控件
     
    }
    return   self ;
    }
    -( void )drawView{
    //文本框
    textField=[[UITextField alloc]
      initWithFrame:CGRectMake( 0 0 ,
    oldFrame.size.width, 
    oldFrame.size.height)];
    textField.borderStyle=borderStyle; // 設置文本框的邊框風格
    [ self  addSubview:textField];
        [textField addTarget: self  action: @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的值顯示或隱藏
     
    [ self  addSubview:listView]; 
    [listView release];
    }
    -( void )dropdown{
    [textField resignFirstResponder];
     if  (showList) { //如果下拉框已顯示,什么都不做
    return ;
     } else  { //如果下拉框尚未顯示,則進行顯示
    //把dropdownList放到前面,防止下拉框被別的控件遮住
     
    [ self .superview bringSubviewToFront: self ];
    [ self  setShowList: YES ]; // 顯示下拉框
    }
    }
    #pragma mark listViewdataSource method and delegate method
    -(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
     return  list.count;
    }
    -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     static  NSString *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;
     return  cell;
    }
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return  oldFrame.size.height;
    }
    //當選擇下拉列表中的一行時,設置文本框中的值,隱藏下拉列表
    -( void )tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSLog(@"select");
    textField.text=(NSString*)[list objectAtIndex:indexPath.row];
    //NSLog(@"textField.text=%@",textField.text);
    [ self  setShowList: NO ];
    }
     -( BOOL )showList{ //setShowList:No為隱藏,setShowList:Yes為顯示
     return  showList;
    }
    -( 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 {
        [ super  dealloc];
    }
    @end
create toolbar using new
  toolbar = [UIToolbar new];
  toolbar.barStyle = UIBarStyleDefault;
  [toolbar sizeToFit];
  toolbar.frame = CGRectMake(0, 410, 320, 50);
 
 
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:UIControlEventValueChang ed];
 
  [self.viewaddSubview:segmentedControl];
 
  [segmentedControl release];

//事件

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

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



圖片:4adf31eat76b2e24823fb&690.png 
 

iOS Programming – 觸摸事件

iphone/ipad鍵盤設計是為屏幕爭取更多的顯示空間,大屏幕在觀看圖片、文字、視頻等方面為用戶帶來了更好的用戶體驗。而觸摸屏幕是iOS設備接受用戶輸入的主要方式,包括單擊、雙擊、撥動以及多點觸摸等,這些操作都會產生觸摸事件。

在Cocoa中,代表觸摸對象的類是UITouch。當用戶觸摸屏幕后,就會產生相應的事件,所有相關的UITouch對象都被包裝在事件中,被程序交由特定的對象來處理。UITouch對象直接包括觸摸的詳細信息。
UITouch類中包含5個屬性:
  window:觸摸產生時所處的窗口。由於窗口可能發生變化,當前所在的窗口不一定是最開始的窗口。
view:觸摸產生時所處的視圖。由於視圖可能發生變化,當前視圖也不一定時最初的視圖。
tapCount:輕擊(Tap)操作和鼠標的單擊操作類似,tapCount表示短時間內輕擊屏幕的次數。因此可以根據tapCount判斷單擊、雙擊或更多的輕擊。
times*****p:時間戳記錄了觸摸事件產生或變化時的時間。單位是秒。
phase:觸摸事件在屏幕上有一個周期,即觸摸開始、觸摸點移動、觸摸結束,還有中途取消。而通過phase可以查看當前觸摸事件在一個周期中所處的狀態。phase是UITouchPhase類型的,這是一個枚舉配型,包含了          
· UITouchPhaseBegan(觸摸開始)
· UITouchPhaseMoved(接觸點移動)
· UITouchPhaseStationary(接觸點無移動)
· UITouchPhaseEnded(觸摸結束)
· UITouchPhaseCancelled(觸摸取消)
UITouch類中包含如下成員函數:
- (CGPoint)locationInView:(UIView *)view函數返回一個CGPoint類型的值,表示觸摸在view這個視圖上的位置,這里返回的位置是針對view的坐標系的。調用時傳入的view參數為空的話,返回的時觸摸點在整個窗口的位置。
- (CGPoint)previousLocationInView:(UIView *)view該方法記錄了前一個坐標值,函數返回也是一個CGPoint類型的值, 表示觸摸在view這個視圖上的位置,這里返回的位置是針對view的坐標系的。調用時傳入的view參數為空的話,返回的時觸摸點在整個窗口的位置。
當手指接觸到屏幕,不管是單點觸摸還是多點觸摸,事件都會開始,直到用戶所有的手指都離開屏幕。期間所有的UITouch對象都被包含在UIEvent事件對象中,由程序分發給處理者。事件記錄了這個周期中所有觸摸對象狀態的變化。
只要屏幕被觸摸,系統就會報若干個觸摸的信息封裝到UIEvent對象中發送給程序,由管理程序UIApplication對象將事件分發。一般來說,事件將被發給主窗口,然后傳給第一響應者對象(FirstResponder)處理。
關於響應者的概念,通過以下幾點說明:
   響應者對象(Response object   響應者對象就是可以響應事件並對事件作出處理。在iOS中,存在UIResponder類,它定義了響應者對象的所有方法。UIApplication、UIView等類都繼承了UIResponder類,UIWindow和UIKit中的控件因為繼承了UIView,所以也間接繼承了UIResponder類,這些類的實例都可以當作響應者。
          第一響應者(First responder)
   當前接受觸摸的響應者對象被稱為第一響應者,即表示當前該對象正在與用戶交互,它是響應者鏈的開端。
   響應者鏈(Responder chain   響應者鏈表示一系列的響應者對象。事件被交由第一響應者對象處理,如果第一響應者不處理,事件被沿着響應者鏈向上傳遞,交給下一個響應者(next responder)。一般來說,第一響應者是個視圖對象或者其子類對象,當其被觸摸后事件被交由它處理,如果它不處理,事件就會被傳遞給它的視圖控制器對象(如果存在),然后是它的父視圖(superview)對象(如果存在),以此類推,直到頂層視圖。接下來會沿着頂層視圖(top view)到窗口(UIWindow對象)再到程序(UIApplication對象)。如果整個過程都沒有響應這個事件,該事件就被丟棄。一般情況下,在響應者鏈中只要由對象處理事件,事件就停止傳遞。但有時候可以在視圖的響應方法中根據一些條件判斷來決定是否需要繼續傳遞事件。
   管理事件分發   視圖對觸摸事件是否需要作處回應可以通過設置視圖的userInteractionEnabled屬性。默認狀態為YES,如果設置為NO,可以阻止視圖接收和分發觸摸事件。除此之外,當視圖被隱藏(setHidden:YES)或者透明(alpha值為0)也不會收事件。不過這個屬性只對視圖有效,如果想要整個程序都步響應事件,可以調用UIApplication的beginIngnoringInteractionEvents方法來完全停止事件接收和分發。通過endIngnoringInteractionEvents方法來恢復讓程序接收和分發事件。
如果要讓視圖接收多點觸摸,需要設置它的multipleTouchEnabled屬性為YES,默認狀態下這個屬性值為NO,即視圖默認不接收多點觸摸。
關於UIView的userInteractionEnabled屬性
如果父視圖為ParentView包含一個Button,如果再ParentView上添加子視圖ChildView,且ChildView蓋住了Button,那么Button就得到不響應了,
為了讓Button響應,可以設置ChildView的userInteractionEnabled = NO;最近被這個問題困擾了很久,開始想用事件傳遞的方法,
重寫類繼承自UIView,最后被這簡單屬性搞定了....
鍵盤透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

狀態欄的網絡活動風火輪是否旋轉
[UIApplication sharedApplication].networkActivityIndicatorVisible,默認值是NO。

截取屏幕圖片
//創建一個基於位圖的圖形上下文並指定大小為CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400)); 

//renderInContext 呈現接受者及其子范圍到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

 //返回一個基於當前圖形上下文的圖片
 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();

 //移除棧頂的基於當前位圖的圖形上下文
UIGraphicsEndImageContext();

//以png格式返回指定圖片的數據
imageData = UIImagePNGRepresentation(aImage);

更改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鍵盤改變顏色
只有這2種數字鍵盤才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad
keyboardAppearance = UIKeyboardAppearanceAlert 
代碼如下:
  1.    NSArray *ws = [[UIApplication sharedApplication] windows];
  2.     for(UIView *w in ws){
  3.         NSArray *vs = [w subviews];
  4.         for(UIView *v in vs){
  5.             if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"]){
  6.                 v.backgroundColor = [UIColor redColor];
  7.             }
  8.         }
  9.     }
從一個界面push到下一界面左上角返回按鈕文字設置
在父viewController中如下設置:
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];
    backbutton.title = @"返回列表";
    self.navigationItem.backBarButtonItem = backbutton;
    [backbutton release];

navigationbar的back鍵觸發其他事件
UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)]; 
[back addTarget:self act

ion:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];
[back setImage:[UIImage imageNamed:@"返回按鈕.png"] forState:UIControlStateNormal];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = loginButtonItem
[back release];
[backButtonItem release];
防止屏幕暗掉鎖屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

將圖片從左到右翻頁效果顯示

    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];
    [imageView setImage:[UIImage imageNamed:@"Bg.jpg"]];
    self.myImageView =imageView;
    [self.view addSubview:imageView];
    [imageView release];
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    [myImageView setFrame:CGRectMake(0, 0, 310, 470)];    
    [UIView commitAnimations];

讓覆蓋在下面層的視圖接受觸摸事件

searchImage.exclusiveTouch = YES;//第一層
searchImage.userInteractionEnabled = NO;
myMapView.exclusiveTouch = NO;//第二層
myMapView.userInteractionEnabled = YES;

View的縮放


NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain];
[UIView beginAnimations:nil context:touchPointValue];
transform = CGAffineTransformMakeScale(0.1,0.21);
firstPieceView.transform = transform;
[UIView commitAnimations];    
點擊 UITextView 輸入文字,光標都從最初點開始
能讓用戶點擊 UITextView 輸入文字時,光標都從最初點開始
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    NSRange range;
    range.location = 0;
    range.length  = 0;
    textView.selectedRange = range;
}

UITextView光標位置的設置
點擊 UITextView 輸入文字,光標都從最初點開始 


更改UITextView的光標的位置:

-(void)textViewDidChangeSelection:(UITextView*)textView
{
NSRange range;
range.location = 0;
range.length = 0;
textView.selectedRange =range;
}
以上是當在UITextView中輸入文字的時候,光標都從最初點開始。


PS:UITextView有一個小BUG,如果其高度小於50的話,輸入的時候其光標會往上偏移,從而看不到光標,如果大於50就不會出現這個問題。
UITextView在光標處添加文字
// 獲得光標所在的位置
int location =contentTextView.selectedRange.location;
// 將UITextView中的內容進行調整(主要是在光標所在的位置進行字符串截取,再拼接你需要插入的文字即可)
NSString *content = contentTextView.text;
NSString *result = [NSStringstringWithFormat:@"%@[姓名變量]%@",[contentsubstringToIndex:location],[contentsubstringFromIndex:location]];
// 將調整后的字符串添加到UITextView上面
contentTextView.text = result;

如何設置UITextView的光標位置
UITextView * m_textInput;
//設置光標到輸入文字的末尾
NSUInteger length = m_textInput.text.length;
m_textInput.selectedRange = NSMakeRange(length,0);                                    

UITextView方法 用法


UITextView限制行數的問題之前試了好多方法,最終解決了,解決方法非常簡單,在UITextViewDelegate中加下面的方法即可:
-(BOOL)textView:(UITextView *)textViewshouldChangeTextInRange:(NSRange)range
 replacementText:(NSString*)text {
  
   if (textView.contentSize.height > 104){
      textView.text = [textView.text substringToIndex:[textView.textlength]-1];
       returnNO;
   }



   return YES;
}




-(void)textViewDidChangeSelection:(UITextView*)textView 
每次輸入都知道

[textView becomeFirstResponder]

(void)textViewDidChange:(UITextView*)textView textView的內容發生改變時,會調用。。再此計算已經輸入的字符個數。

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)rangereplacementText:(NSString *)text; {

if([@"\n" isEqualToString:text] == YES) {
 
 [textViewresignFirstResponder];
 
 returnNO;
 
 }
 
 returnYES;
}

- (BOOL)textView:(UITextView*)textView 
shouldChangeTextInRange:(NSRange)rangereplacementText:(NSString *)text;
textview根據光標插入數據  

UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
//定位光標

    NSRange range = [opinion selectedRange];
NSMutableString *top = [[NSMutableString allocinitWithString:[opinion text]];
NSString *addName = [NSString stringWithFormat:@"%@",cell.textLabel.text];
    [top insertString:addName atIndex:range.location];
    opinion.text = top;
    [top release];

用NStimer每隔一定時間刷新界面
NSTimer *addEnemyTimer;
addEnemyTimer=[NSTimer scheduledTimerWithTimeInterval:(3.0) target:self selector:@selector(addEnemy) userInfo:nil repeats:YES];


可以嘗試使用一個單獨的線程來實現

多點觸摸:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
當一個或多個手指觸碰屏幕時,發送touchesBegan:withEvent:消息。
 
當一個或多個手指在屏幕上移動時,發送touchesMoved:withEvent:消息。
當一個或多個手指離開屏幕時,發送touchesEnded:withEvent:消息。

iphone中的UITouch    
手指在屏幕上能達到的精度和鼠標指針有很大的不同。當用戶觸擊屏幕時,接觸
    區域實際上是橢圓形的,而且比用戶想像的位置更靠下一點。根據觸摸屏幕的手指、手指的尺寸、手指接觸屏幕的力量、手指的方向、以及其它因素的不同,
其“接觸部位”的尺寸和形狀也有所不同。底層的多點觸摸系統會分析所有的這些信息,為您計算出單一的觸點。

    UIResponder 是所有響應者對象的基類,
    它不僅為事件處理,而且也為常見的響應者行為定義編程接口。UIApplication、UIView、和所有從UIView 派生出來的UIKit 類(包括UIWindow)都直接或間接地繼承自UIResponder類。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    NSUInteger numTaps = [touch tapCount];
    if (numTaps < 2) {
    [self.nextResponder touchesBegan:touches withEvent:event];
    } else {
    [self handleDoubleTap:touch];
    }
    }

    缺省情況下,視圖會接收觸摸事件。但是,您可以將其userInteractionEnabled
    屬性聲明設置為NO,關閉事件傳遞的功能。

    在一定的時間內關閉事件的傳遞。應用程序可以調用UIApplication 的
    beginIgnoringInteractionEvents 方法,並在隨后調用endIgnoringInteractionEvents 方法來實現這個目的。

    缺省情況下,視圖只接收多點觸摸序列的第一個觸摸事件,而忽略
    所有其它事件。如果您希望視圖處理多點觸摸,就必須使它啟用這個功能。在代碼或Interface Builder 的查看器窗口中將視圖的multipleTouchEnabled 屬性設置為YES,就可以實現這個目標。
    將事件傳遞限制在某個單獨的視圖上。缺省情況下,視圖的exclusiveTouch 屬性被設置為NO。將這個屬性設置為YES 會使相應的視圖具有這樣的特性:即當該視圖正在跟蹤觸摸動作時,窗口中的其它視圖無法同時進行跟蹤,它們不能接收到那些觸摸事件。
    多點觸摸:
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

    當一個或多個手指觸碰屏幕時,發送touchesBegan:withEvent:消息。
    當一個或多個手指在屏幕上移動時,發送touchesMoved:withEvent:消息。
    當一個或多個手指離開屏幕時,發送touchesEnded:withEvent:消息。
    當觸摸序列被諸如電話呼入這樣的系統事件所取消時,發送touchesCancelled:withEvent:消息。
    上面這些方法都和特定的觸摸階段(比如UITouchPhaseBegan)相關聯,該信息存在於UITouch 對象的phase 屬性聲明中。
    為了處理給定階段的事件,響應者對象常常從傳入的集合參數中取得一或多個UITouch 對象,然后考察這些對象的屬性或取得它們的位置(如果需要處理所有觸摸對象,可以向該NSSet 對象發送anyObject 消息)。UITouch 類中有一個名為locationInView:的重要方法,如果傳入self 參數值,它會給出觸摸動作在響應者坐標系統中的位置(假定該響應者是一個UIView 對象,且傳入的視圖參數不為nil)。另外,還有一個與之平行的方法,可以給出觸摸動作之前位置(previousLocationInView:)。UITouch 實例的屬性還可以給出發生多少次觸
    碰(tapCount)、觸摸對象的創建或最后一次變化發生在什么時間(times*****p)、以及觸摸處於什么階段(phase)。

    - (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
    {
    UITouch *touch = [touches anyObject];
    if ([touch tapCount] == 2) {
    CGPoint tapPoint = [theTouch locationInView:self];
    // Process a double-tap gesture
    }
    }
    在touchesEnded:withEvent:方法中,當觸擊次數為一時,響應者對象就向自身發送一個performSelector:withObject:afterDelay:消息,其中的選擇器標識由響應者對象實現的、用於處理單擊手勢的方法;第二個參數是一個NSValue 或NSDictionary 對象,用於保存相關的UITouch 對象;時延參數則表示單擊和雙擊手勢之間的合理時間間隔。
    在touchesBegan:withEvent:方法中,如果觸擊次數為二,響應者對象會向自身發送一個cancelPreviousPerformRequestsWithTarget:消息,取消當前被掛起和延期執行的調用。如果觸碰次數不為二,則在指定的延時之后,先前步驟中由選擇器標識的方法就會被調用,以處理單擊手勢。
Iphone開發-NSRunLoop概述和原理
1.什么是NSRunLoop?
我們會經常看到這樣的代碼:


- (IBAction)start:(id)sender
{
pageStillLoading = YES;
[NSThread detachNewThreadSelector:@selector(loadPageInBackground:)toTarget:self withObject:nil];
[progress setHidden:NO];
while (pageStillLoading) {
[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
[progress setHidden:YES];
}
  這段代碼很神奇的,因為他會“暫停”代碼運行,而且程序運行不會因為這里有一個while循環而受到影響。在[progress setHidden:NO]執行之后,整個函數像暫停了一樣,停在循環里面,等loadPageInBackground里面的操作都完成了以后,
才讓[progress setHidden:YES]運行。這樣做就顯得簡單,而且邏輯很清晰。如果不這樣做,就需要在loadPageInBackground里面表示load完成的地方調用[progress setHidden:YES],顯得代碼不緊湊而且容易出錯。
那么具體什么是NSRunLoop呢?其實NSRunLoop的本質是一個消息機制的處理模式。如果你對vc++編程有一定了解,在windows中,有一系列很重要的函數SendMessage,PostMessage,GetMessage,
這些都是有關消息傳遞處理的API。但是在你進入到Cocoa的編程世界里面,我不知道你是不是走的太快太匆忙而忽視了這個很重要的問題,Cocoa里面就沒有提及到任何關於消息處理的API,
開發者從來也沒有自己去關心過消息的傳遞過程,好像一切都是那么自然,像大自然一樣自然?在Cocoa里面你再也不用去自己定義WM_COMMAD_XXX這樣的宏來標識某個消息,
也不用在switch-case里面去對特定的消息做特別的處理。難道是Cocoa里面就沒有了消息機制?答案是否定的,只是Apple在設計消息處理的時候采用了一個更加高明的模式,那就是RunLoop。
利用NSRunLoop阻塞NSOperation線程
使用NSOperationQueue簡化多線程開發中介紹了多線程的開發,我這里主要介紹一下使用NSRunLoop阻塞線程。
主要使用在NStimer定時啟用的任務或者異步獲取數據的情況如socket獲取網絡數據,要阻塞線程,直到獲取數據之后在釋放線程。
下面是線程中沒有使用NSRunLoop阻塞線程的代碼和執行效果:
線程類:
#import <Foundation/Foundation.h> 
@interface MyTask : NSOperation {     

@end
#import "MyTask.h" 
@implementation MyTask 
-(void)main     
{      
    NSLog(@"開始線程=%@",self);      
    [NSTimer timerWithTimeInterval:2 target:self selector:@selector(hiandeTime:) userInfo:nil repeats:NO];      
}      
-(void)hiandeTime:(id)sender      
{      
    NSLog(@"執行了NSTimer");      
}      
-(void)dealloc      
{      
    NSLog(@"delloc mytask=%@",self);      
    [super dealloc];      

@end
線程添加到隊列中:


- (void)viewDidLoad     
{      
    [super viewDidLoad];      
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];      
    MyTask *myTask=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask];      
    MyTask *myTask1=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask1];      
    MyTask *myTask2=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask2];      
    [queue release];      
}

執行結果是:
2011-07-25 09:44:45.393 OperationDemo[20676:1803] 開始線程=<MyTask: 0x4b4dea0>   
2011-07-25 09:44:45.393 OperationDemo[20676:5d03] 開始線程=<MyTask: 0x4b50db0>    
2011-07-25 09:44:45.396 OperationDemo[20676:1803] 開始線程=<MyTask: 0x4b51070>    
2011-07-25 09:44:45.404 OperationDemo[20676:6303] delloc mytask=<MyTask: 0x4b4dea0>    
2011-07-25 09:44:45.404 OperationDemo[20676:5d03] delloc mytask=<MyTask: 0x4b50db0>    
2011-07-25 09:44:45.405 OperationDemo[20676:6303] delloc mytask=<MyTask: 0x4b51070>

可以看到,根本沒有執行NSTimer中的方法,線程就釋放掉了,我們要執行
NSTimer中的方法,就要利用NSRunLoop阻塞線程。下面是修改后的代碼:

-(void)main     
{      
    NSLog(@"開始線程=%@",self);      
    NSTimer *timer=[NSTimer timerWithTimeInterval:2 target:self selector:@selector(hiandeTime) userInfo:nil repeats:NO];      
    [timer fire];      
    while (!didDisconnect) {      
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];      
    }      
}
執行結果如下:
2011-07-25 10:07:00.543 OperationDemo[21270:1803] 開始線程=<MyTask: 0x4d16380>     
2011-07-25 10:07:00.543 OperationDemo[21270:5d03] 開始線程=<MyTask: 0x4d17790>      
2011-07-25 10:07:00.550 OperationDemo[21270:6303] 開始線程=<MyTask: 0x4d17a50>      
2011-07-25 10:07:00.550 OperationDemo[21270:1803] 執行了NSTimer      
2011-07-25 10:07:00.551 OperationDemo[21270:5d03] 執行了NSTimer      
2011-07-25 10:07:00.552 OperationDemo[21270:6303] 執行了NSTimer      
2011-07-25 10:07:00.556 OperationDemo[21270:6503] delloc mytask=<MyTask: 0x4d16380>      
2011-07-25 10:07:00.557 OperationDemo[21270:6303] delloc mytask=<MyTask: 0x4d17790>      
2011-07-25 10:07:00.557 OperationDemo[21270:5d03] delloc mytask=<MyTask: 0x4d17a50>
我們可以使用NSRunLoop進行線程阻塞。
ASIHTTPRequest 一款強大的HTTP包裝開源項目   
ASIHTTPRequest,是一個直接在CFNetwork上做的開源項目,提供了一個比官方更方便更強大的HTTP網絡傳輸的封裝。
特色功能如下:
1,下載的數據直接保存到內存文件系統里
2,提供直接提交(HTTP POST)文件的API
3,可以直接訪問與修改HTTP請求與響應HEADER
4,輕松獲取上傳與下載的進度信息
5,異步請求與隊列,自動管理上傳與下載隊列管理機
6,認證與授權的支持
7,Cookie
8,請求與響應的GZIP
9,代理請求


下面來兩個小例子:
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request start];
NSError *error = [request error];
if (!error) {
    NSString *response = [request responseString];
}


當你需要添加更多的請求信息時,如,添加個請求Header:
[request addRequestHeader:@"name" value:@"Jory lee"];

添加Post請求時的健值:
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

設置HTTP
的授權帳號:
[request setUsername:@"username"];
[request setPassword:@"password"];


一個異步請求:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];

// Use when fetching binary data
NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
   

在我們數據獲取的過程中,如果數據源復雜,一個請求隊列是必不可少的:
- (IBAction)grabURLInTheBackground:(id)sender
{
if (![self queue]) {
[self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
}

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
}

- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}

- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
   
ASIHTTPRequest使用介紹

SIHTTPRequest,是一個直接在CFNetwork上做的開源項目,提供了一個比官方更方便更強大的HTTP網絡傳輸的封裝。

一、介紹
特色功能如下:
1.下載的數據直接保存到內存文件系統里
2.提供直接提交(HTTP POST)文件的API
3.可以直接訪問與修改HTTP
請求與響應HEADER
4.輕松獲取上傳與下載的進度信息
5.異步請求與隊列,自動管理上傳與下載隊列管理機
6.認證與授權的支持
7.Cookie
8.請求與響應的GZIP
9.代理請求
ASIHTTPRequest -Main classes介紹:
1.ASIHTTPRequest:處理與服務器的基本交互,包括下載上傳,認證,cookies以及進度查看。
2.ASIFormDataRequest:是ASIHTTPRequest子類,主要處理post事件,它能使post更加簡單。
3.ASINetworkQueue:是NSOperationQueue子類,當處理多個請求時可以使用,如果每次都是單個請求就不必使用。
4.ASIDownloadCache:該類允許ASIHTTPRequest從服務器傳遞cookie。
ASIHTTPRequest -Support classes介紹:
1.ASIInputStream:當使用ASIHTTPRequest上傳數據時使用,如果工程中用了ASIHTTPRequest,就一定要include這個類。
2.ASIAuthenticationDialog:該類允許ASIHTTPRequest連接到服務器時呈現登錄框。在所有iPhone OS工程中都要使用,Mac OS工程中可以不用。
3.Reachability:相信很多人對這個類已經很熟悉了,當在你程序中偵測網絡狀態時它將非常有用。
ASIHTTPRequest -Protocols and configuration介紹:
1.ASIHTTPRequestDelegate:該協議指定了ASIHTTPRequest的delegate可能需要實現的方法,所有方法都是optional。
2.ASIProgressDelegate:該協議列出了uploadProgressDelegate和downloadProgressDelegate可能需要實現的方法,所有方法為optional。
3.ASICacheDelegate:該協議指定了download cache必須實現的方法。如果你要寫你自己的download cache,確保實現required方法。
4.ASIHTTPRequestConfig.h:該文件定義了編譯時所有的全局配置選項。使用該文件中的方法可以在控制台中輸出request正在進行的任務.

 
原址:http://www.cocoachina.com/bbs/read.php?tid=73570
 

Iphone 開發常用代碼   

 
 
更改cell選中的背景
    UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
    cell.selectedBackgroundView = myview;

在數字鍵盤上添加button:
//定義一個消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注冊一個觀察員 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];//返回應用程序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];
    }
}

正則表達式使用
被用於正則表達式的字串必須是可變長的,不然會出問題

將一個空間放在視圖之上
[scrollView insertSubview:searchButton aboveSubview:scrollView];

從本地加載圖片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src='0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];

從網頁加載圖片並讓圖片在規定長寬中縮小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];
將網頁加載到webview上通過javascript獲取里面的數據,如果只是發送了一個連接請求獲取到源碼以后可以用正則表達式進行獲取數據
NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";
NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];

用NSString怎么把UTF8轉換成unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];

View自己調用自己的方法:
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黃色段為方法名,和延遲幾秒執行.

顯示圖像:
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];

WebView:
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
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左上部的狀態欄顯示的轉動的圖標指示有背景發生網絡的活動。
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;

動畫:一個接一個地顯示一系列的圖象
NSArray *myImages = [NSArray arrayWithObjects: [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; //animationImages屬性返回一個存放動畫圖片的數組
myAnimatedView.animationDuration = 0.25; //瀏覽整個圖片一次所用的時間
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 動畫重復次數
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];

動畫:顯示了something在屏幕上移動。注:這種類型的動畫是“開始后不處理” -你不能獲取任何有關物體在動畫中的信息(如當前的位置) 。如果您需要此信息,您會手動使用定時器去調整動畫的X和Y坐標
這個需要導入QuartzCore.framework
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
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"];

Draggable items//拖動項目
Here's how to create a simple draggable image.//這是如何生成一個簡單的拖動圖象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// 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. Now instantiate the new class as you would any other new image and add it to your view
//實例這個新的類,放到你需要新的圖片放到你的視圖上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];

線程:
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
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"];
}
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];

Alerts
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];

Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews])
{
if (anImage.tag == 1)
        { // do something }
}
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM