MVC模式:(model+view+controller):是一種幫你把代碼功能和顯示劃分出來的設計模式;
model:較爲底層的數據引擎,負責管理實體中所繼承的數據;
view:和用戶交互界面;
controller:鏈接兩者的橋樑;
cocoa frameworks 有兩個框架:
foundation
foundation 是cocoa中最基本的一些類;再mac應用程序中負責對象管理,內存管理,容器等相關數據;
uikit:
uikit:爲程序提供可視化的底層構架,包括窗口,視圖,控件類和管理這些對象的控制器。這一層中的其它框架容許你訪問用戶聯繫人和圖片信息,以及設備上的加速器和其它硬件特徵;
code4app.com
UI(User Interface)編程
建立ios項目
1.打開iOS中的application;
2.UIViewController:視圖控件,經過點擊,觸摸來控制程序
3.UIView :視圖;
4.在項目中建立一個文件。在 iOS的cocoa touch建立一個
ulviewcontrollersubclass類而後在AppDelegate.m中找到application函數,在 self.window.backgroundColor = [UIColor whiteColor];後寫以下代碼
RootViewCotroller *rvc=[[RootViewCotroller alloc]initWithNibName:@
"RootViewCotroller"
bundle:nil];
self.window.rootViewController=rvc;
[rvc release];
代碼含義:建立根控件,並把新建立的根控件賦值給窗口的根控件;注意釋放;
5.label控件的建立和屬性:
能夠用視圖界面建立;而後修改屬性;
6.代碼實現label
1.IBOutlet :是個宏。控件和根界面控件內容創建聯繫
2.atomic:原子操做;線成保護;就是在幾個線程中調用同一段內容時致使所用內容混亂,進行枷鎖機制
nonatomic:不加鎖機制;能提升效率;
把控件打包,並和界面添加的控件創建聯繫:
3.在RootViewCotroller.m文件中在viewDidLoad(加載函數)函數中設置lable的屬性;
4.iPhone 橫向320 豎向480 橫條佔20; 因此通常是320*460
建立給label並在屏幕上定位
CGRect rect={0,100,100,40};
//建立定位結構體;
座標原點是左上角;四個參數分別是距左框的距離;距上框的距離;label控件的寬度,高度;
UILabel *label=[[UILabel alloc] initWithFrame:rect];
UILabel *label=[[UILabel alloc]
可一直接生成UIrect;
initWithFrame:CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)]
5.UIView * 指全部可視控件;
6.設置背景色
[label1 setBackgroundColor:[UIColor blueColor]];
7.設置label的字體;
[label2 setFont:[UIFont systemFontOfSize:20]];
label1.font=[UIFont italicSystemFontOfSize:30];
8.設置字體的顏色
label2.textColor=[UIColor redColor];
9.設置字體的對齊方式;
label1.textAlignment=UITextAlignmentLeft;
10.自動調整字體
label1.adjustsFontSizeToFitWidth=YES;
當文字數量多時能夠自動調整字體大小
若是不設置就會變成省略;
字體省略方式:
label2.lineBreakMode=UILineBreakModeHeadTruncation;
這個是截去頭,還有尾截,和中間截去;
label2.lineBreakMode=UILineBreakModeClip;
表示在已有控件寫多少是多少,不寫省略符
label1.lineBreakMode=UILineBreakModeCharacterWrap;
字符換行,指只要須要換行就換行不考慮單詞的總體性;
label1.lineBreakMode=UILineBreakModeWordWrap;
以一個整個單詞換行,不容許把整個單詞分開寫到不一樣的行;保持單詞完整性;
設置自動調整的最小限制
label1.minimumFontSize=10;
11.設置行數:
label1.numberOfLines=3;
注:若是行高不夠的話它不能顯示完整;
字體省略方式
12.設置高亮顏色
label1.highlightedTextColor=[UIColor whiteColor];
設置高亮的狀態時的顏色;
label1.highlighted=YES;
把label設置爲高亮狀態;
13.設置陰影色
label1.shadowColor=[UIColor blackColor];
設置陰影顏色;
label1.shadowOffset=CGSizeMake(-2,-2 );
設置陰影位置;是相對字體的位置;
14.IOPhone的圖標默認大小時57*57;
9.4週二
1. IBAction 時
void
型的,爲了鏈接某個觸發;
2.button建立
button1=[UIButton buttonWithType:UIButtonTypeRoundedRect]
注:這樣建立的button不是alloc出來的不用釋放;
後面參數時button 的外觀;
3.button設置位置:
button1.frame=CGRectMake(120, 280, 80, 40);
4.button 設置title
[button1 setTitle:@
"click here"
forState:UIControlStateNormal];
注:因爲button繼承view control因此它能夠設置狀態;
狀態的做用?
答:能夠在不一樣狀態下展現不一樣的button 特色;
1.高亮狀態下設置
[button1 setTitle:@
"click ready"
forState:UIControlStateHighlighted];
2.禁用狀態設置
[button1 setTitle:@
"forbid using"
forState:UIControlStateDisabled];
button1.enabled=NO;
button設置成不可用,可是還能夠更改button 的屬性
5. 設置button的title的屬性;
button1.titleLabel.font=[UIFont systemFontOfSize:20];
注:button是複合了label因此能夠調用title label,設置它的 文本屬性就是設置button的文本屬性;
6設置 顏色
[button1 setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
7.給button添加事件
[button1 addTarget:self action:@selector(onclick) forControlEvents:UIControlEventTouchUpInside];
addTarget:指觸發的對象; action:觸發的事件; forControlEvets:是表示如何點擊按鈕觸發;
8.局部聲明button,如何使用button使其執行動做;
在事件函數頭傳遞button對象;誰調用它就傳遞誰的地址;
-(
void
)onclick:(UIButton *)seder
[button addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchUpInside];
注意:傳遞調用函數帶參數有冒號;
9.添加圖片
UIImage *image=[UIImage imageNamed:@
"03.gif"
];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setBackgroundImage:image1 forState:UIControlStateHighlighted];
10.獲得圖片大小
CGSize size=image.size;
NSLog(@
"%f %f"
,size.width,size.height);
11.讓button一直處於選擇狀態;
button.selected=YES;
button會一直處於一個狀態而不改變? 到底什麼意思
12. 判斷button狀態執行操做;
if
(button.state==UIControlStateNormal){
}
13.移出事件
[sender removeTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchDragOutside];
14.點擊滑動的妙用;能夠在做程序時加入實現觸屏效果;
[button addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchDragInside];
[button addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchDragOutside];
9.6週四
UIView (視圖)
1.什麼是uiview
在應用程序中看的見摸的着的是視圖。至關於java中容器;
viewController至關於底板;
2.建立視圖
UIView *view=[[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 420)];
3.將視圖添加到父視圖
[self.view addSubview:view];
注意:子視圖是父視圖的子類,後添加的視圖在最上曾;
4.在視圖view中添加label(label 是view的子類)
[view addSubview:label];
注:因爲ui中的控件都是視圖,因此能夠在任意視圖加載其餘視圖;
把一些視圖裝到另外一個視圖是爲了保證視圖的總體性;
注:在button上添加label點擊label就是點擊button label至關於透明;而在上添button就是點誰誰響應;
5.
CGRectframe :座標
CGRectbounds:邊界
button.bounds=CGRectMake(0, 0, 50, 50);
CGPointcenter:中點
該是圖的中點在父視圖的相對座標;
button.center=CGPointMake(160, 230);
指視圖的中心位置在父視圖的相對位置
獲得視圖的終點座標:
button.center.x;
button.center.y;
6.視圖層次
視圖子類是個數組;
視圖先添加的在下,後添加在上;
交換視圖位置:
[button1 exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
1.遍歷視圖
for
(UILabel * l in button1.subviews) {
l.text=[NSString stringWithFormat:@
"%d"
,i++];
}
2.插入視圖
[button1 insertSubview:label3 atIndex:1];
將視圖label3插入到視圖button1的第二位;
[button1 insertSubview:label2 aboveSubview:label1];
將視圖label2插到label1上;
[button1 insertSubview:label1 belowSubview:label3];
3.將視圖從父類視圖中移出;
[label2 removeFromSuperview];
4.[button1
delete
:label2];
5.將視圖放到最上層 ;
[button1 bringSubviewToFront:label1];
注:寫代碼時把子視圖寫到一塊,父視圖寫到一塊
6.把視圖放到最上下層
[button1 sendSubviewToBack:label1];
7.判斷某個視圖是某個視圖的子視圖 返回類型是
bool
類型;
[label1 isDescendantOfView:button1];
7.tag 視圖的標誌; 能夠標誌視圖。是set 和get函數,設置和取得能夠用「.」操做
button1.tag=1;
8.label1.superview 表示label1的父視圖;
9. 隱藏視圖 :label1.hidden=YES; 默認爲no。
應用:可讓視圖重疊換燈片放映,或動畫;若是父視圖隱藏,子視圖也隨之消失
10.視圖可能會超出父視圖的範圍;這時能夠更改父視圖邊界屬性裁減出邊界 的子視圖
button1.clipsToBounds=YES;
UIImageView
1.初始化:
UIImageView *imageview=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@
"2.jpg"
]];
imageview.frame=CGRectMake(20, 20, 140, 220);
imageview.contentMode=UIViewContentModeScaleAspectFit;
讓添加的圖片按比例填充;
3.imageview和label都不能觸發事件 可是能夠給他們添加事件
當單擊判斷失敗 在觸發單擊;先判斷,不知道是單擊仍是雙擊
UITapGestureRecognizer *tgr=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onclick)];
tgr.numberOfTapsRequired=1;
tgr.numberOfTapsRequired=2;
[tag addTarget:self action :@selecter(press:)];
[imageview addGestureRecognizer:tgr];
4.
imageview.UserInteractionEnabled=YES;
5.三中圖片填充方式
imageview.contentMode=UIViewContentModeScaleAspectFit;
imageview.contentMode=UIViewContentModeScaleAspectFill;
imageview.clipsToBounds=YES;
imageview.contentMode=UIViewContentModeScaleToFill;
6.建立視圖還能夠在appDelegate.m中的application中聲明實現
7. 子視圖按某中形式隨父視圖擴大或縮小;不一樣的擴大縮小方式特色能夠或
labelsub.autoresizingMask=UIViewAutoresizingFlexibleWidth;
labelsub.autoresizingMask=UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
控制視圖按比例的開關;
labelsub.autoresizesSubviews=NO;
MVC:設計思想: model:內存數據 view :可視控件;controller:控制代碼;
單例:從頭至尾使用的類
RootController *rvc=[[RootController alloc]initWithNibName:@
"RootController"
bundle:nil];
之後初始化要不建立xib文件初始化方法是:
RootController *rvc=[[RootController alloc]init];
kvo/kvc:?
notification:?
窗口:
iphono內存佔用量不超過20Mb
全屏作法 1.記下此時的控件fram
2.修改控件的大小,使其全屏
3.把改圖像拉到頂層;
4.修改tag
字體新設置:
label.font=[UIFont fontWithName:@
"宋體"
size:30];
timer
1.建立定時器,一但建立就開始運行;
NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changLabel) userInfo:nil repeats:YES];
2,定時器中止;一旦中止就釋放,至關於release;
[timer invalidate];
3,打開定時器
[timer fire]
4.動畫效果
'
UITextField:對話框 一樣是個view
1.建立
UITextField *field=[[UITextField alloc] initWithFrame:CGRectMake(40, 20, 250, 60)];
2.設置邊框
UITextField *field=[[UITextField alloc] initWithFrame:CGRectMake(40, 20, 250, 60)];
3.在文本框後面設置清除鍵
field.clearButtonMode=UITextFieldViewModeAlways;
4.設置初始文本
field.placeholder=@
"username"
;
5。設置文本變爲隱藏;
field.secureTextEntry=YES;
6.設置textfield的自定義函數
首先在.h文件中提交協議 <UITextFieldDelegate>
這樣就能夠自定義textfield 函數;注:自定義函數若是是返回
bool
類型的函數說明這個函數是一個監聽函數;自定義都是進行某些動做時自動調用;
7.-(
void
)textFieldDidBeginEditing:(UITextField *)textField
當文本框進入編輯模式時自動調用
8.退出編輯模式時調用函數;
-(
void
)textFieldDidEndEditing:(UITextField *)textField
{
( (UILabel *)[self.view.subviews objectAtIndex:0]).text=textField.text;
}
9.點擊鍵盤上
return
後調用的函數
-(
BOOL
)textFieldShouldReturn:(UITextField *)textField
10.關閉鍵盤函數;
[textField resignFirstResponder];
return
NO;
11.限定輸入字符的長度函數
-(
BOOL
)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{ //textfield表示誰調用該函數,
if
(string.length>0)
return
textField.text.length<10; //而textField.text的值是尚未加入剛輸入的string
return
YES;
}
9.10 第九周
多控制器操做:
一.多控制器間的切換;
思想:1.在每一個視圖控制器界面添加按鈕點擊觸發事件建立新的視圖控制器;而後把當前控制器交給新建的控制器;
2.在新建的視圖控制器中等使用完該控制器後,把控制器釋放;因爲建立是在前一個控制器中釋放的因此這裏釋放不是簡單的release;
方法:一 1.在父控制器中建立新控制器,並把但前的控制界面交給新控制器
ViewController* vc2=[[ViewController2 alloc] init];
vc2.view.frame=CGRectMake(0,0,320,460);
[self.view addSubview:vc2.view];
[self addChildViewController:vc2];
注:因爲這樣vc2 是在原控制器上加載因此它會默認流出原視圖導航欄,要想讓新控制器所有佔滿屏幕就要更改視圖的大小;
2. 而後用完vc2在最後把vc2從原控制器中移出
[self.view removeFromSuperview];
[self removeFromParentViewController];
注:因爲建立vc2時原有的控制器可vc2關聯,原有的view和vc2的view關聯;因此在清理時得把這兩項分別清理;
注:這中添加清理的方法使用高版本;爲了程序的適用性一般用第二種方法;
二: 1.在父控制器中建立新控制器;並把當前的控制器設置爲vc2,並添加動畫效果
ViewController* vc2=[[ViewController2 alloc] init];
[self presentModalViewController:vc2 animated:YES];
2 在用完vc2時移出該控制器;
[self dismissModalViewControllerAnimated:YES];
動畫效果:只要把新的位置改變放到這些代碼之間;
[UIView beginAnimations:nil context:nil];//動畫設置開始;
[UIView setAnimationDuration:0.2];//設置動畫時間;
text.frame=CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)//對象的新狀態;
[ UIView commitAnimations];//開始動畫;
9。11週二
注:系統對象不開闢空間不能打印retaincount本身聲明的類的對象不開闢空間能夠打印retaincount
導航條UINavigationBar
1.導航條按鈕初始化三種方法:
1.普通初始化
UIBarButtonItem *rigthButton=[[[UIBarButtonItem alloc] initWithTitle:@
"next"
style:UIBarButtonItemStylePlain target:self action:@selector(click:)] autorelease];
第一個參數是按鈕標題;第二個參數是按鈕的樣式;第三個參數是觸發事件調用那個類中的方法第四個參數是觸發的事件
2.用圖片初始化
UIBarButtonItem *rightButtton= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@
"5.png"
] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
注:這樣初始化的按鈕有按鈕框,圖片存在按鈕框裏要想只顯示圖片要自定義按鈕而後用按鈕初始化;如第三種方法;
3.自定義控件初始化
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@
"5.png"
] forState:UIControlStateNormal];
建立button 按鈕,樣式設置爲普通,也就是沒有樣式;
button.frame=CGRectMake(0, 0, 30, 30);
注:必須設置button 的frame不然不顯示
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
給button添加事件
UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithCustomView:button];
初始化導航條button
4.運用系統功能按鈕初始化uibarbutton
UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(click:)];
2.添加副標題
self.navigationItem.prompt=@
"subtile"
; 導航條高度是44;
3.把導航條按鈕設置成數組;可多加按鈕,按鈕一多會把別的控件擠偏;可是不能覆蓋;若是加的太多隻能顯示先加入的;
self.navigationItem.rightBarButtonItems=[NSArray arrayWithObjects:<#(id), ...#>, nil]
注:UIBarButtonItem 有些屬性和unbutton不同,UIBarButtonItem不能設置
4.設置導航條色調
self.navigationController.navigationBar.tintColor=[UIColor purpleColor];
5.顏色色透明度
1.黑色透明度
self.navigationController.navigationBar.barStyle=UIBarStyleBlackTranslucent;
2.其餘顏色透明度
self.navigationController.navigationBar.translucent=YES;
self.navigationController.navigationBar.alpha=0.8
slider.frame=self.navigationController.navigationBar.bounds;
重點
6.更改導航條背景
if
(__IPHONE_OS_VERSION_MIN_REQUIRED>=__IPHONE_5_0) {
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@
""
] forBarMetrics:UIBarMetricsDefault];
}
若是是5.0如下的能夠建立類別
@implementation UINavigationBar(Custom)
-(
void
)drawRect:(CGRect)rect{
UIImage *image=[UIImage imageNamed:@
""
];
[image drawInRect:rect];
}
7.隱藏導航條
[self.navigationController setNavigationBarHidden:YES animated:YES];
8.直接跳轉到某頁
1.建立數組把控制頁面所有加載進來;
NSMutableArray *array=[NSMutableArray arrayWithArray:self.navigationController.viewControllers];
2.設置跳轉到哪頁
[self.navigationController popToViewController:[array objectAtIndex:0] animated:YES];
可以設置的常項
建立一個可變空數組;
NSMutableArray *array1=[[NSMutableArray alloc]initWithCapacity:0];
用數組設置navigationController的ViewControllers
self.navigationController.viewControllers=array;
9.在子導航條中去除自帶得返回上一級得button
self.navigationItem.hidesBackButton=YES;
ToolBar工具條
1.建立工具條:爲單個viewcontroller添加toolbar
UIToolbar *toobar=[[UIToolbar alloc] initWithFrame:CGRectMake(0,372,320, 44)];
注:必定要注意建立導航條後當前的viewcontroller的座標原點已經改變是加上導航條後的的高度;導航條的高度是44;
toolbar.tintColor=[UIColor purpleColor];
toolbar的顏色設置;和導航條設置同樣;
toobar.hidden=NO;
注:toolbar的hidden屬性默認是yes,因此加toolbar要把hidden設置爲no;
2. 在導航條中有toolbar屬性;因此要想每頁都加toolbar 就能夠在這裏把導航條的toolbar的hidden屬性設置爲no;
];
UINavigationController *nv=[[UINavigationController alloc]initWithRootViewController:vc];
nv.toolbarHidden=NO;
nv.toolbar.tintColor=[UIColor purpleColor];
[nv setNavigationBarHidden:YES animated:YES];
3.把按鈕寫成一個數組而後添加到toolbar
[array addObject:button];
[self setToolbarItems:array animated:YES];
4.驗證兩個coloer屬性;
tinkcoloer:
9.12 週三
UISlider 滑條控件
滑條初始化:
UISlider *sl=[[UISlider alloc]initWithFrame:CGRectMake(30, 60, 280, 30)];
1.滑條的高度不用設置由於系統默認 ;可是能夠設置背景圖改變滑條的高度;具體看滑條的圖片設置
建立label用來顯示滑動的數值
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
view控件的tag屬性能夠做爲區分視圖的標誌想查找它時能夠在另外一個函數中寫
UILabel *label=(UILabel *)[self.view viewWithTag:100];
label.tag=100;
設置滑條的最大值和最小值;
sl.minimumValue=0.0;
sl.maximumValue=20.0;
給滑條添加事件,因爲滑條的值是可變的因此監聽它時用值改變事件監聽,之後通常遇到值能夠不斷改變的view控件要用值改變事件監聽;
[sl addTarget:self action:@selector(valuechang:) forControlEvents:UIControlEventValueChanged];
sl.value=10.0;
設置大小端圖像;
sl.maximumValueImage=[UIImage imageNamed:@
"5.png"
];
設置滑條軌跡的顏色
sl.minimumTrackTintColor=[UIColor purpleColor];
sl.maximumTrackTintColor=[UIColor redColor];
sl.thumbTintColor=[UIColor greenColor];
[sl setThumbImage:[UIImage imageNamed:@
"5.png"
] forState:UIControlStateNormal];
[sl setMinimumTrackImage:[UIImage imageNamed:@
"5.png"
] forState:UIControlStateNormal];
[sl setMaximumTrackImage:[UIImage imageNamed:@
"5.png"
] forState:UIControlStateNormal];
簡單的滑條觸發事件測試:滑條值的改變顯示在label控件上;
-(
void
)valuechang:(UISlider *)sender
{
UILabel *label=(UILabel *)[self.view viewWithTag:100];
label.text=[NSString stringWithFormat:@
"%.0f"
,sender.value];
}
UISwitch:開關控件
初始化
switch
對象
UISwitch * _swith=[[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
給with添加事件注意 事件控制是UIControlEventValueChanged
[_swith addTarget:self action:@selector(sw:) forControlEvents:UIControlEventValueChanged];
設置with的打開時背景色
_swith.onTintColor=[UIColor blackColor];
注:不用設置
switch
的寬高。由於時系統默認;設置沒有做用;
給
switch
添加
switch
事件:狀態改變一次觸發一次
-(
void
)sw:(UISwitch *)swith
{
if
(
switch
.on==YES)
NSLog(@
"yes"
);
else
NSLog(@
"no"
);
}
UIActivityIndicatorView:加載緩控件
UIActivityIndicatorView *aiv=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
設置當中止時隱藏
aiv.hidesWhenStopped=NO;
設置旋轉圖標的樣式。一共有三種
aiv.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge;
設置緩衝圖標的顏色 注:要先設置樣式在設置顏色,由於樣式是帶顏色,能覆蓋之前的顏色;
aiv.color=[UIColor blueColor];
緩衝圖標開始,中止動畫;
[aiv startAnimating];
[aiv stopAnimating];
UIProgressView:進度條
初始化進度條
UIProgressView *pgv=[[UIProgressView alloc] initWithFrame:CGRectMake(50, 100, 220, 0)];
設置進度條的tag屬性;
pgv.tag=100;
pgv.progressViewStyle=UIProgressViewStyleBar;
pgv.progressTintColor=[UIColor purpleColor];
pgv.trackTintColor=[UIColor blackColor];
pgv.progressImage=[UIImage imageNamed:@
""
];
pgv.trackImage=[UIImage imageNamed:@
""
];
//用時間控制器模擬時間進度條;
[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(refresh:) userInfo:nil repeats:YES];
//用函數對進度條作試驗
-(
void
)refresh:(NSTimer *)timer
{
UIProgressView *pv=(UIProgressView *)[self.view viewWithTag:100];
[pv setProgress:pv.progress+0.1 animated:YES];
if
(pv.progress==1) {
NSLog(@
"%d"
,[timer retainCount]);
[timer invalidate];
NSLog(@
"%d"
,[timer retainCount]);
}
UITextView 文本編輯器
文本編輯器和文本框同樣有代理函數在.h文件開頭需引入;
@interface ViewController : UIViewController<UITextViewDelegate>
它的代理函數和文本框的基本相同,不一樣的有兩個
-(
void
)textViewDidChange:(UITextView *)textView:(UITextView *)textView
-(
void
)textViewDidChangeSelection:(UITextView *)textView
注:在調用代理函數時必定要textview的代理設置爲調用函數所在的類;
文本框的一些屬性設置:
1.初始化文本框
UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
2.文本框的顏色,對齊方式,字體設置
textView.textColor=[UIColor grayColor];
textView.textAlignment=UITextAlignmentLeft;
textView.font=[UIFont systemFontOfSize:30];
3。自動糾錯關閉;
textView.autocorrectionType=NO;
4.大寫模式;除此以外還能夠設置字母不大寫;句首字母大寫。單詞開頭字母大寫; textView.autocapitalizationType=UITextAutocapitalizationTypeAllCharacters;
5.鍵盤模式:
textView.keyboardType=UIKeyboardTypePhonePad;//打電話模式
textView.returnKeyType=UIReturnKeyGo;返回模式變爲go
//根據輸入框須要輸入的內容不一樣要設置鍵盤的樣式
UIStepper 計步器
1.初始化
UIStepper *stepper=[[UIStepper alloc]initWithFrame:CGRectMake(100, 200, 100, 40)];
2.給stepper添加觸發事件,仍是注意 forControlEvents:UIControlEventValueChanged的設置
[stepper addTarget:self action:@selector(stepper:) forControlEvents:UIControlEventValueChanged];
3.設置stepper的最大最小值
stepper.minimumValue=0;
stepper.maximumValue=50;
4.
stepper.autorepeat=YES;
stepper.wraps=YES;
stepper.stepValue=2;
stepper.continuous=NO;
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(50, 50, 100, 50)];
label.font=[UIFont systemFontOfSize:30];
[self.view addSubview:label];
label.tag=100;
-(
void
)stepper:(UIStepper *)stepper
{
UILabel *label=(UILabel *)[self.view viewWithTag:100];
label.text=[NSString stringWithFormat:@
"%f"
,stepper.value];
}
UISegmentedControl 分段控制器;
1.分段控制器初始化
UISegmentedControl *sc=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@
"a"
,@
"b"
,@
"c"
,[UIImage imageNamed:@
"5.png"
], nil]];
2 分段控制器設置frame
sc.frame=CGRectMake(100, 100, 150, 40);
3. 爲分段控制器添加監聽事件;
[sc addTarget:self action:@selector(sc:) forControlEvents:UIControlEventTouchUpInside];
4。控制類型控制類型一共有四種;
sc.segmentedControlStyle=UISegmentedControlStyleBordered;
5。按鈕自動彈起開啓;默認是no;
sc.momentary=YES;
6。添加新按鈕;能夠是文字,或圖像;
[sc insertSegmentWithTitle:@
"e"
atIndex:3 animated:YES];
[sc insertSegmentWithImage:<#(UIImage *)#> atIndex:<#(NSUInteger)#> animated:<#(
BOOL
)#>]
7.在段控制器中區分點擊那個按鈕的個屬性
int
i=sc.numberOfSegments;
int
j=sc.selectedSegmentIndex;
[sc removeSegmentAtIndex:j animated:YES];
[sc removeAllSegments];
UIGesture 手勢事件
1.移動手勢
1.建立移動手勢的對象:
UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
2.把此對象添加到操做的對象中;
[imagview addGestureRecognizer:pan];
3.實現移動對象的方法
-(
void
)pan:(UIPanGestureRecognizer *)pan
{
CGPoint point=[pan translationInView:self.view];
//這個函數是獲得觸點在屏幕上與開始觸摸點的位移值
imagview.center=CGPointMake(imagview.center.x+point.x, imagview.center.y+point.y);
//讓圖像的中心位置變化;中心變化圖像位置就移動了 ,可是注意位移時若是不清空translation就會多移動一倍;因此每次要讓pan的位置零;
[pan setTranslation:CGPointMake(0, 0) inView:self.view];
}
2.擴大縮小手勢
1.建立擴大縮小手勢的對象 在建立時就帶了要觸發的事件 手勢器
UIPinchGestureRecognizer *pinch=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
2.記錄下開始圖像的大小,在擴大縮小函數時使用;緣由是擴大尺寸是在圖像的現有大小上乘,而圖像的尺寸是變化的因此會使圖像擴大縮小的太過火;因此紀錄原圖像大小一直在這個基礎上擴大 size=CGSizeMake(imagview.bounds.size.width,imagview.bounds.size.height );
3.圖像添加擴大縮小手勢;
[imagview addGestureRecognizer:pinch];
4.圖像擴大縮小手勢觸發的事件;
-(
void
)pinch:(UIPinchGestureRecognizer *)pinch
{
改變圖像的大小;pinch.scale是觸摸點的相對於原有位置的位移量的倍數。
imagview.bounds=CGRectMake(0, 0,size.width*pinch.scale, size.height*pinch.scale);
爲了防止每次擴大縮小都要從原圖開始,因此操做結束釋放觸點一次就要把當前的尺寸記下,下次變化在這個基礎上改變;
if
(pinch.state==UIGestureRecognizerStateEnded) {
size=CGSizeMake(imagview.bounds.size.width, imagview.bounds.size.height);
}
gesture.scale=1.0f;
3.旋轉手勢
1.旋轉角度對象的初始化
UIRotationGestureRecognizer *rotation=[[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)];
2.給旋轉圖像添加旋轉對象
[imagview addGestureRecognizer:rotation];
3.旋轉時觸發的函數
-(
void
)rotation:(UIRotationGestureRecognizer *)rotation
{
讓圖像旋轉某個角度,這個交度使相對原圖旋轉的角度。因此必須有個判斷語句,若是釋放一次觸點就要把當前位置記下,不然圖像還會回到原來狀態;
imagview.transform=CGAffineTransformMakeRotation(f+rotation.rotation);
if
(rotation.state==UIGestureRecognizerStateEnded) {
f=f+rotation.rotation;
}
}
4.tap的一些屬性
能夠給image添加tap事件
tap.numberOfTapsRequired=2;
tap.numberOfTouchesRequired=2;
5.觸摸時自動調用的觸摸函數一共有四個
觸點事件調用時UITouch對象產生後自動調用的屬性;因爲單擊的話只有一共對象;因此不論有幾個touch對象都時指當前鼠標觸點?那爲何還要建立觸點對象呢?而anyobject以外還能作什麼
1. 觸摸開始觸發的事件
-(
void
)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@
"began"
);
創建觸摸對象 觸摸對象是任意觸點;可是事實是當前鼠標點擊的點;可是怎麼獲得另外一個點的座標?
UITouch *touch=[touches anyObject];
if
(touch.tapCount==1)
{
NSLog(@
"這是一個單擊事件"
);
}
else
if
(touch.tapCount==2)
{
NSLog(@
"這是一個雙擊事件"
);
}
CGPoint point=[touch locationInView:self.view];
NSLog(@
"%f %f"
,point.x,point.y);
2.觸摸事件結束觸發事件
-(
void
)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@
"end"
);
}
3.cancell實在移動時忽然被其餘進程打斷時調用。好比突來電話
-(
void
)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@
"cancel"
);
}
4.觸點移動時觸發的事件;
-(
void
)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGPoint point=[touch locationInView:self.view];
UIImageView * imageView=(UIImage *)[self.view viewWithTag:101];
CGRect
NSLog(@
"move"
);
}
[performSelector:@selector(single Tag)withObject:nil afterDelay:delaytime]
9.13週四
1.各個控制器間的關係:
window 的rootviewcontroller能夠是uinavigationcontroller ,uitabbarcontroller ,uiviewcontroller
uinavigationconroller 上能夠添加uiviewcontroller
uitabbarcontroller上能夠添加uiviewcontrolller 也能夠添加uinavigationcontroller
到此基本上控制器的關係弄清了;
1.UITabBarController :標籤控制器,分欄控制器
當uitabbarcontroller含的uitabbaritem不少時,編譯器會自動隱藏以省略號表示,點擊省略號就能夠查看不顯示的item
1.初始化:
UITabBarController *tc=[[UITabBarController alloc]init];
2.建立視圖控制器而後建立 UITabBarItem並把它賦給視圖控制器的 tabBarItem
ViewController *vc=[[[ViewController alloc]init]autorelease];
UITabBarItem *item=[[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemSearch tag:0];
注:能夠自定義item 也能夠用系統中定義好的;
vc.tabBarItem=item;
3.建立導航條;用於放人UITabBarController 由此可知uitabbarcontronller和uinavigationcontroller的包含關係;
UINavigationController *nc=[[UINavigationController alloc]initWithRootViewController:vc];
4.添加導航控件和視圖控件;
tc.viewControllers= [NSArray arrayWithObjects:nc,vc1,vc2, nil];
5.讓根控制器爲標籤控制器
self.window.rootViewController=tc;
2.解決不顯示第二個之後的標籤問題
1.緣由:若是把每一個控制器的標籤生成寫在viewdidload裏面因爲爲了節省內存開始只會加載一個控制器。因此只能顯示第一個標籤;
ViewController1 *vc1=[[[ViewController1 alloc]init]autorelease];
vc1.view.backgroundColor=[UIColor blueColor];
2.解決方法:1.init函數中生成控制器標籤生成代碼;在建立控制器時就會執行;
2. 在appdelegate中生成控制器的標籤
3.在appdelegate 中調用控制器的函數
3.本地存儲: NSUserDefaults:一旦運行數據就會被存儲下來,每次運行程序之前的紀錄下來的數據仍然有;
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
//爲本地存儲添加數據;相似於字典的用法
[userDefault setObject:@
"adba"
forKey:@
"key"
];
[userDefault synchronize]; 同步了才能夠保存到本地的
NSString * str=[userDefault objectForKey:@
"key"
];
NSLog(@
"%@"
,str);
- (
void
)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(@
"You selected: %d"
,tabBarController.selectedIndex);
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setInteger:tabBarController.selectedIndex forKey:@
"LAST_PAGE"
];
[ud synchronize];
}
- (
void
)viewWillAppear:(
BOOL
)animated;
- (
void
)viewDidAppear:(
BOOL
)animated;
- (
void
)viewWillDisappear:(
BOOL
)animated;
- (
void
)viewDidDisappear:(
BOOL
)animated;
4.數據字典:NSDictionary:用於存儲數據能夠和數組聯合起來用;
1.字典的初始化方法
1.直接用數值初始化:
NSDictionary *dic1=[[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@
""
,@
""
, nil] forKeys:[NSArray arrayWithObjects:@
""
,@
""
, nil]] ;
2.用數組初始化
NSArray *array=[[NSArray alloc]initWithObjects:@
"23"
,@
"100"
,@
"zhang"
,nil];
NSArray *array2=[[NSArray alloc] initWithObjects:@
"年齡"
,@
"體重"
,@
"姓名"
, nil];
NSDictionary *dic1=[[NSDictionary alloc]initWithObjects:array forKeys:array2];
3.用其餘字典初始化
NSDictionary *dic=[[NSDictionary alloc]initWithDictionary:dic1];
4.用網絡URL初始化
NSDictionary *dic5=[NSDictionary alloc]initWithContentsOfURL:<#(NSURL *)#>
2.經過key來找到對應的值;
NSLog(@
"%@"
,[dic objectForKey:@
"key"
]);
3.建立動態字典 用法和普通字典同樣;
NSMutableDictionary *dic3=[NSMutableDictionary dictionaryWithCapacity:0];
4.爲動態字典添加內容;
[dic2 setObject:@
"180"
forKey:@
"身高"
];
[dic2 setObject:@
"56"
forKey:@
"weight"
];
[dic2 setObject:@
"13"
forKey:@
"age"
];
NSNumber 數值對象
1.初始化數值對象 用一個基礎數據類型初始化,如整形,浮點,字符均可以;
NSNumber *num=[NSNumber numberWithInt:vc.tabBarItem.tag ];
2.把數值對象添加到數組中;
[array addObject:num];
3.把nsstring類型轉換成值;和把數值類型轉換成整形
int
i=1;
NSString *str=[NSString stringWithFormat:@
"%d"
,i];
int
a=[str intValue];
UITabBarController的代理函數;
uitabbarcontroller 中當item不少時會有省略;還能夠調整uitabbaritem的排放順序調整在主頁顯示的頁面;這時會須要tabbarcontroller 的代理類
1.當某個viewcontroller被選擇時觸發的事件;
應用:每當頁面顯示時有些提示信息……..
-(
void
)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(@
"didSelectViewController"
);
NSLog(@
"%d"
,viewController.tabBarItem.tag);
}
2.在某個viewcontroller選擇時觸發的事件
-(
BOOL
)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
NSLog(@
"shouldSelectViewController:"
);
NSLog(@
"%d"
,viewController.tabBarItem.tag);
return
YES;
}
3 將要結束用戶自定義item時;既點擊導航欄中的done時調用用法:能夠提示用戶確實要這樣更改嗎。
-(
void
)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray *)viewControllers changed:(
BOOL
)changed
{
NSLog(@
"willEndCustomizingViewControllers"
);
NSLog(@
"%d"
,changed);
}
4.將開始進行用戶自定義item時調用;既點擊了導航欄中的edit時調用此函數;
-(
void
)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray *)viewControllers
{
}
5.結束用戶自定義item後調用既單擊了done ;用法能夠紀錄此時的新的item用於永久性更改,下次運行此程序保持這個狀態;
-(
void
)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(
BOOL
)changed
{
NSMutableArray *array=[NSMutableArray arrayWithCapacity:0];
for
(UIViewController *vc in viewControllers) {
NSNumber *num=[NSNumber numberWithInt:vc.tabBarItem.tag ];
[array addObject:num];
}
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
[userdefault setObject:array forKey:@
"num"
];
NSLog(@
"didEndCustomizingViewController"
);
}
如何保存用戶更改的uitabbaritem位置?
1.在用戶用編輯item順序後執行done,這時在調用的didEndCustomizingViewControllers 函數傳遞的參數viewControllers 紀錄了此時新的排列順序;這時要用本地存儲記下這個順序;注意由於每一個viewcontroller在初始化時設置了本身的tag值,因此只記下tag值就能夠找到對應的viewcontroller
-(
void
)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(
BOOL
)changed
{
初始化可變數組用於存儲tag值
NSMutableArray *array=[NSMutableArray arrayWithCapacity:0];
遍歷新設置的控制器順序;並把tag值按順序存儲到可變數組中
for
(UIViewController *vc in viewControllers) {
NSNumber *num=[NSNumber numberWithInt:vc.tabBarItem.tag ];
[array addObject:num];
} 定義本地存儲對象;
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
把可辨數組存入到本地存儲中
[userdefault setObject:array forKey:@
"num"
];
NSLog(@
"didEndCustomizingViewController"
);
}
2. 在加載函數中能夠先判斷本地存儲是否有數據;若是沒有就是用戶還未設置過,那item順序要按加載順序排列;若是非空的話就把本地存儲的數據的賦值給viewcontrollers;
NSMutableArray *array=[NSMutableArray arrayWithCapacity:0];
for
(
int
i=0; i<6; i++) {
UIViewController *vc=[[UIViewController alloc]init];
[array addObject:vc];
UITabBarItem *item=[[UITabBarItem alloc]initWithTitle:[NSString stringWithFormat:@
"vc%d"
,i+1] image:[UIImage imageNamed:@
"1.png"
] tag:i];
vc.tabBarItem=item;
[item release];
[vc release];
}
UITabBarController *tabbar=[[UITabBarController alloc]init];
tabbar.viewControllers=array;
注:沒有alloc的對象必定不要release;如button通常建立不用alloc;注意注注意
9.14 週五
實現鍵盤彈起時頁面也跟着彈起鍵盤的高度
1.基本思想:
1. 建立兩個通知用於監聽鍵盤彈起和落下
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//name是監聽的信號;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.在監聽鍵盤彈起的事件中記下鍵盤高度,而後把view提升鍵盤高度
-(
void
)keyboardWillShow:(NSNotification *)noti
{ 鍵盤彈起時觸發的事件;
NSDictionary *dic=[noti userInfo];
CGRect rect=[[dic objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
float
h=rect.size.height;
NSLog(@
"%f"
,h);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
self.view.frame=CGRectMake(0, 20-h, 320, 460);
[UIView commitAnimations];
}
3.收起鍵盤 鍵盤彈出和收起是隨文本編輯開始和退出自動彈出和收起,因此要想讓文本框退出編輯模式必須有個事件觸發,而在touchesbegan的系統函數中只要鼠標點擊就能觸發,因此通常在這個裏面讓textfield退出編輯模式;
[ resignFirstResponder]; 就是textfield退出編輯模式的函數;
-(
void
)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITextField * textfield=(UITextField *)[self.view viewWithTag:100];
[textfield resignFirstResponder];
}
4.不使用鍵盤時讓view以動畫跳下來;
-(
void
)keyboardWillHide:(NSNotification *)noti
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.20];
self.view.frame=CGRectMake(0, 20, 320, 460);
[UIView commitAnimations];
}
彈出消息框
注:彈出消息框所用代理爲UIAlertViewDelegate 這是提示框, 這個不用添加到窗口的!!!
1.建立消息框對象
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@
"error"
message:@
"賬號錯誤"
delegate:self cancelButtonTitle:@
"取消"
otherButtonTitles:@
"肯定"
, nil];
讓消息框展現出來
[alertview show];
[alertview release];
2.在消息框對象的代理函數中執行操做 消息框有四個代理函數,點擊函數最經常使用
-(
void
)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
經過傳遞過來的button序號知道那個button進行了操做執行相應的命令
if
(buttonIndex==0) {
self.view.backgroundColor=[UIColor yellowColor];
}
else
self.view.backgroundColor=[UIColor brownColor];
}
從相冊和相機獲取圖片
思想: 1.建立獲取圖片按鈕和接收圖像的的視圖控件
imageview =[[UIImageView alloc]initWithFrame:CGRectMake(100, 80, 100, 100)];
[self.view addSubview:imageview];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(100, 190, 120, 20);
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
2.在button觸發的事件中生成UIActionSheet對象去選擇從哪裏獲取圖片
-(
void
)buttonClick
{
UIActionSheet *as=[[UIActionSheet alloc]initWithTitle:@
"選擇圖片來源"
delegate:self cancelButtonTitle:@
"取消"
destructiveButtonTitle:@
"相機"
otherButtonTitles:@
"相冊"
, nil];
//能夠生成多個按鈕
[as showInView:self.view];
展現這個動做頁面;
[as release];
}
3.經過調用UIActionSheet的代理函數獲取圖片;因此頭文件必須聲明他的代理通常用到是點擊函數,經過傳遞按鈕的排列序號知道那個按鈕被點擊觸發相應的事件
-(
void
)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if
(buttonIndex==2) {
return
;
}
// 取消按鈕序號是2,因此若是指針是2,代表觸發了取消,注意對應的序號要和建立時一致;
UIImagePickerController *pc=[[UIImagePickerController alloc]init];
//建立圖片獲取控制器;根據點擊按鈕不一樣從不一樣的資源獲取圖片;
if
(buttonIndex==0 && TARGET_IPHONE_SIMULATOR)
{
[pc release];
return
;
}
if
(buttonIndex==0){
pc.sourceType=UIImagePickerControllerSourceTypeCamera;
}
else
if
(buttonIndex==1)
{
pc.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
pc.delegate=self;
//把控制器交給圖像資源獲取控制器
[self presentModalViewController:pc animated:YES];
[pc release];
}
在系統中的圖片獲取器中點擊按鈕能夠觸發的事件
-(
void
)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
imageview.image=image;
[picker dismissModalViewControllerAnimated:YES];
}
-(
void
)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
9.17 第十週 週一
UIScrollView 滾動視圖
注:蘋果的內存複用機制:視圖很大超過了屏幕顯示的範圍,在顯示的只是屏幕上的內容,爲了減小內存使用把不現實的那用從內存中去除;
1.滾動視圖的初始化
UIScrollView *sv=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
frame:是滾屏在視圖上佔用的大小;
2.給滾動視圖添加控件時,若是控件有事件響應的話,系統設置了一個定時器,若是在限定事件內拖動的話,該控件就失去了響應機會,拖動視圖也會跟着拖動;
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(100, 100, 100, 50);
3.設置滾屏的大小,這個屬性很重要 顯示的是內容的大小 體現了滾動視圖的經典
sv.contentSize= CGSizeMake(320, 460*2);
滾屏的真實大小;
4.初始位置設置
sv.contentOffset=CGPointMake(90, 90);
5.豎直和水平滾動條是否顯示;默認時顯示滾動條
sv.showsVerticalScrollIndicator=NO;
sv.showsHorizontalScrollIndicator=NO;
6.反彈效果的設置;設爲yes後能夠反彈;設爲no就不能反彈;
sv.bounces=YES;
sv.alwaysBounceHorizontal=YES;
sv.alwaysBounceVertical=YES;
7.設置爲不可滾動;即便大於框架
sv.scrollEnabled=NO;
[sv addSubview:imageView];
[self.view addSubview:sv ];
sv.contentSize=CGSizeMake(260*4, 400);
sv.pagingEnabled=YES;
sv.bounces=YES;
sv.contentOffset=CGPointMake(100, 0);
使用:代理的三部曲,每個協議方法都是這麼來作的
遵照協議(什麼控制器遵照什麼協議 寫在尖括號裏面)
委託代理(A.delegate=self)
實現方法(完成的方法);
8.滾動條的代理函數
1.當屏幕滾動時調用的函數
-(
void
)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(@
"%f %f"
,scrollView.contentOffset.x,scrollView.contentOffset.y);
}
2. 將要開始拖動時調用
-(
void
)scrollViewWillBeginDragging:(UIScrollView *)scrollView
3.滾動結束後調用 手指擡起開始減速的瞬間 開始回調
-(
void
)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@
"endDrag"
);
}
4.滾屏結束時調用
-(
void
)scrollViewDidEndDragging:(UIScrollView *)scrollView
5.滾屏將開始減速時調用
-(
void
)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
用一個類來封裝一下,封裝就是派生出一個類,寫本身的類,
9.用滾動視圖來顯示圖片的縮放;注:滾屏只能執行單一功呢,要麼讓他作縮放功呢,要麼讓他實現滾屏;
1.建立滾動視圖
super viewDidLoad];
UIScrollView *sv=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
2.設置最大最小縮放
sv.maximumZoomScale=5.0;
sv.minimumZoomScale=0.5;
3. 建立視圖控件,而後添加到滾屏中。
imageview=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@
"5.png"
]]];
imageview.frame=CGRectMake(100, 100, 50, 50);
[sv addSubview:imageview];
[imageview release];
4.用到滾屏的函數要給它設置代理
sv.delegate=self;
處理用戶響應事件,須要重載那三個觸摸的方法,開始,觸摸到,末尾,
5.在滾屏的放大縮小函數中寫實現功能
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
static
int
i=0;
if
(scrollView!=myScrollView) {
return
[scrollView.subviews objectAtIndex:i];
i++;
}
else
return
NULL;
}
封裝一個類達到的效果 簡化代碼,頗有好處
10.運用滾動屏實現廣告條展現;
設計思想:滾動廣告起始和最後廣告條實現不間斷的無限循環;因此要多家一個視圖,最後一個視圖和第一個同樣,這樣能夠保證不間斷;
UIScrollView *sv=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
sv.contentSize=CGSizeMake(320, 200*9);
sv.scrollEnabled=NO;
//視圖的可滾動屬性設爲no不可滾動;
sv.tag=100;
[self.view addSubview:sv];
sv.showsVerticalScrollIndicator=NO;
for
(
int
i=0; i<9; i++) {
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, i*200, 320, 200)];
imageview.image=[UIImage imageNamed:[NSString stringWithFormat:@
"17_%d.jpg"
,i]];
[sv addSubview:imageview];
[imageview release];
}
//建立計時器來控制圖片定時更替
NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
}
-(
void
)timer:(NSTimer *)timer
{
UIScrollView *sv=(UIScrollView *)[self.view viewWithTag:100];
//當滾屏滾到最後一幅圖時,讓滾屏從頭開始
if
(sv.contentOffset.y==200*8)
{
sv.contentOffset=CGPointMake(0, 0);
}
[sv setContentOffset:CGPointMake(0, sv.contentOffset.y+200) animated:YES];
}
UIPageControl 分頁顯示 頁面控制器
1.初始化對象
UIPageControl *pc=[[UIPageControl alloc]initWithFrame:CGRectMake(0, 440, 80, 20)];
2.設置頁數
pc.numberOfPages=4;
pc.tag=100;
3.爲分頁點添加事件
[pc addTarget:self action:@selector(pc:) forControlEvents:UIControlEventTouchUpInside];
4.在滑動頁面時,爲每頁定位 開發者沒法判斷用戶判斷到哪一頁,因此只有委託UIScrollView的方法
使用這個函數以前要實現UIScrollViewDelegate代理
-(
void
)scrollViewDidScroll:(UIScrollView *)scrollView
{
UIPageControl *pc=(UIPageControl *)[self.view viewWithTag:100];
pc.currentPage=scrollView.contentOffset.x/320;
}
5.注意要想給滾屏分頁,除了建立分頁對象還要讓滾屏設置分頁屬性
sv.pagingEnabled=YES;
-(
void
)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int
pageNumber=scrollView.contentOffset.x/320;
myPageontrol.currentPage=pageNumber;
}
9.18週二
必須實現的
@required
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
UITableView 表視圖
1.初始化表格控件
UITableView * tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460-44) style:UITableViewStyleGrouped];
tableview.tag=100;
2.給表格控件添加代理。注意它有兩個代理
tableview.delegate=self;
tableview.dataSource=self;
3.表格控件的代理函數
1.行數
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return
dataarray.count;
}
1,複用機制;要重點了解;
2,只有一列,兩列的話就是有兩個tableView;
3,有數據源對象,代理對象,tableView自己的對象;
2.cell單元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
爲每一個單元個加一個標誌,便於取得
NSString *strID=@
"ID"
;
從表格對象中獲得移出屏幕得對象;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:strID];
if
(cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strID]autorelease];
}
//添加圖片
cell.imageView.image=[UIImage imageNamed:@
"5.png"
];
cell.detailTextLabel.text=@
"open"
;
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
// 設置cell文本 從數組中取出來 能夠把文字統一放到數組裏面去
cell.textLabel.text = [dataarray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=@
"open"
;
return
cell;
}
刪除或添加cell 先刪除數據,再添加數據源 ,分爲兩步, 由於它有兩個代理 ,其中一個就是數據源代理
3. 段數
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return
3;
}
4.行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return
50;
}
5.段頭標題
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return
@
"abc"
;
}
6.段尾標題
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return
@
"tial"
;
}
7.刪除和添加
設置每一個單元格的可編輯屬性默認是yes因此當讓它處於編輯模式時這個函數能夠不寫
-(
BOOL
)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return
YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return
UITableViewCellEditingStyleInsert;//插入模式;
}
-(
void
)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
刪除時既要從屏幕上刪除,又要從數組中刪除,
[dataarray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
注意:若是表格分不少段,就必須分段操做;
1.分幾段,就建立幾個數組,以防刪除不一樣段內容相互影響,致使崩潰;
2.在給每段單元格添加標題時也要分段添加;返回行數時也要按段來返回數組的行數;
3.在刪除單元格時要根據段不一樣刪除不一樣的數組元素;
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return
@
"2334"
;
}
7.爲選擇cell添加操做;下面操做爲點擊就會跳到新頁面;做爲選擇cell操做的時候來用的
-(
void
)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIViewController *vc=[[UIViewController alloc]init];
vc.title=[NSString stringWithFormat:@
"%d"
,indexPath.row];
[self.navigationController pushViewController:vc animated:YES];
}
8.
- (
void
)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UISearchBar * search = (UISearchBar *)[self.view viewWithTag:102];
if
([search isFirstResponder]) {
[search resignFirstResponder];
}
}
9.爲表格添加索引,點擊就會跳到對應位置,分段的話每一個標記表明一段
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return
[NSArray arrayWithObjects:@
"a"
,@
"b"
,@
"c"
, nil];
}
10.移動某個cell
-(
BOOL
)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return
YES;
}
-(
void
)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
NSString *str=[dataarray objectAtIndex:sourceIndexPath.row];
if
(sourceIndexPath.row<destinationIndexPath.row){
[ dataarray insertObject:str atIndex:destinationIndexPath.row+1 ] ;
[dataarray removeObjectAtIndex:sourceIndexPath.row];
}
else
{
[dataarray insertObject:str atIndex:destinationIndexPath.row];
[dataarray removeObjectAtIndex:sourceIndexPath.row+1];
}
}
注意有導航條時table的高要減掉導航條的高;
@interface VC01 : UIViewController <UITableViewDelegate, UITableViewDataSource>
9.19 週二
搜索條通常搜索條
-(
void
)viewDidLoad
{
[super viewDidLoad];
dataArray=[[NSArray alloc]initWithObjects:@
"dwew"
,@
"dfas"
,@
"aads"
,@
"we"
, nil];
注:在搜索設置時數組建立必定要用alloc;並且release 要在最後的dealloc中;由於數組用於更新數據,不斷的使用若是不用alloc建立可能會被釋放致使數組不可用;
_tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
_tableview.delegate=self;
_tableview.dataSource=self;
注:寫tableview 的協議;
[self.view addSubview:_tableview];
UISearchBar *search=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 88)];
search.delegate=self;
注:注意添加uisearchbar的協議;
mSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[mSearchBar setTag:102];
_mTableView.tableHeaderView = mSearchBar;
search.showsScopeBar=YES;
search.scopeButtonTitles=[NSArray arrayWithObjects:@
"a"
,@
"b"
,@
"c"
, nil];
注:添加範圍條;兩個函數必須連用;要對其添加事件要在下面函數中添加,這個事件是在點擊button時觸發
-(
void
)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
search.showsCancelButton=YES;
注:添加取消鍵
search.showsSearchResultsButton=YES;
注:設置搜索鍵 出發事件要和下面的函數連用 通常用於撤銷鍵盤實現搜索功能;
-(
void
)searchBarSearchButtonClicked:(UISearchBar *)searchBar
注:將搜索條添加到tableview中;
_tableview.tableHeaderView=search;
}
// 添加取消按鈕,點擊取消按鈕時觸發;
-(
void
)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
searchBar.text=@
""
;
}
// 若是設置搜索列表鍵爲真,將添加了搜索列表鍵到搜索列表的後面,點擊時觸這個事件;
-(
void
)searchBarResultsListButtonClicked:(UISearchBar *)searchBar{
searchBar.text=@
"resultslistbutton"
;
}
//點擊鍵盤上的搜索鍵時觸發;
-(
void
)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self searchBar:searchBar textDidChange:searchBar.text];
}
//當添加了範圍界定條時點擊上面的按鈕觸發
-(
void
)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
if
(selectedScope==0) {
searchBar.text=@
"a"
;
}
else
if
(selectedScope==1){
searchBar.text=@
"b"
;
}
else
searchBar.text=@
"c"
;
[self searchBar:searchBar textDidChange:searchBar.text];
//調用本身的函數;對數據進行搜索;今後也得知,非鍵盤輸入的數據要搜索必須經過調用搜索函數出發,或者在鍵盤狀態加入非鍵盤輸入的數據;
}
//返回表格的行數;根據是不是搜索狀態還非搜索狀態反會不一樣的數據
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if
(isSearch==YES) {
return
searchArray.count;
}
else
return
dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@
"ID"
];
if
(cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@
"ID"
]autorelease];
}
if
(isSearch==YES) {
NSLog(@
"%@"
,searchArray);
cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];
}
return
cell;
}
//搜索條中的內容改變時調用;但有個問題就是一旦開始搜索取消後原內容不顯示由於這個函數只有搜索條中輸入值時才調用;因此搜索取消不顯示原有數據;可是若是在結束編輯中調用此函數就不會出現此狀況;
可是此時若是有取消鍵的話又必須在取消鍵中添加內容讓取消後清空搜索框並加載原又數據;因此下面的三個函數是聯繫起來的
-(
void
)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if
(searchBar.text==nil||[searchBar.text isEqualToString:@
""
]) {
isSearch=NO;
[_tableview reloadData];
}
NSPredicate *predicate=[NSPredicate predicateWithFormat:@
"SELF contains [cd] %@"
,searchBar.text];
self.searchArray=[dataArray filteredArrayUsingPredicate:predicate];
isSearch=YES;
[_tableview reloadData];
}
-(
void
)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
[self searchBar:searchBar textDidChange:searchBar.text];
}
-(
void
)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{ searchBar.text=@
""
;
isSearch=NO;
[_tableview reloadData];
[searchBar resignFirstResponder];
}
運用搜索控制器來實現搜索功能
-(
void
)viewDidLoad
{
dataarray=[[NSArray alloc]initWithObjects:@
"da"
,@
"dee"
,@
"ded"
,@
"rtt"
, @
"esdf"
,@
"effy"
,@
"qqo"
,@
"ett"
,@
"sdfa"
,@
"dfg"
,nil];
注:建立搜索數組,數組必須用alloc初始化並且不能被release;
tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
tableview.delegate=self;
tableview.dataSource=self;
tableview.tag=100;
注:要爲tableview添加tag屬性便於知道搜索狀態應爲處於搜索狀態時搜索控制器就會覆蓋住表格框;因此經過判斷此時是的tableview是那個能夠知道更新那個數組數據;
[self.view addSubview:tableview];
[tableview release];
UISearchBar *searchbar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
tableview.tableHeaderView=searchbar;
注:建立搜索展現控制器 把導航條添加進去;把文本控制設置爲本類;
searchdisplay=[[UISearchDisplayController alloc]initWithSearchBar:searchbar contentsController:self];
注:設置代理,和搜索資源搜索代理;
searchdisplay.delegate=self;
searchdisplay.searchResultsDataSource=self;
searchdisplay.searchResultsDelegate=self;
注意:此時搜索控制器不用釋放,由於這個搜索器須要不斷被調用;
[searchbar release];
}
根據此時那個tableview被使用返回數據;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if
(tableView.tag==100) {
return
dataarray.count;
}
return
searcharray.count;
}
//設置單元格;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@
"ID"
];
if
(cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@
"ID"
];
}
if
(tableView.tag==100) {
cell.textLabel.text=(NSString *)[dataarray objectAtIndex:indexPath.row];
}
else
cell.textLabel.text=(NSString *)[searcharray objectAtIndex:indexPath.row];
return
cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return
3;
}
-(
BOOL
)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSPredicate *predicate=[NSPredicate predicateWithFormat:@
"SELF contains [cd] %@"
,searchString];
self.searcharray=(NSArray *)[dataarray filteredArrayUsingPredicate:predicate];
NSLog(@
"%@"
,searcharray);
return
YES;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return
[NSArray arrayWithObjects:UITableViewIndexSearch,@
"a"
,@
"b"
,@
"c"
,nil];
//注意這裏添加了一個搜索,因此搜索指針對應發生改變;在下面的函數返回時要注意
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
if
(index==0) {
[tableView setContentOffset:CGPointMake(0, 0)];
}
return
index-1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return
[NSString stringWithFormat:@
"%d"
,section];
}
注意:有些對象沒有被釋放要寫dealloc函數;
設置控件的收起和放下
(
void
)viewDidLoad
{
[super viewDidLoad];
array=[[NSArray alloc]initWithObjects:@
"小紅"
,@
"小梅"
,@
"小李"
, nil];
tableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
tableview.delegate=self;
tableview.dataSource=self;
tableview.sectionHeaderHeight=30;
[self.view addSubview:tableview];
[tableview release];
p[0]=1;//p是有兩個元素的整形數組作爲開關;若是設置幾段須要幾個開關,就讓數組元素個數是幾
p[1]=1;
}
//根據數組元素的值肯定段是打開仍是收起;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if
(p[section]==0) {
return
0;
}
return
array.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return
2;
}
//建立表格單元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@
"ID"
];
if
(cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@
"ID"
]autorelease];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return
cell;
}
//爲表格的段頭添加view讓此view加載label和button,併爲button添加事件用於控制開關的打開和關閉;既置0和置1;
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
view.backgroundColor=[UIColor blueColor];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
label.backgroundColor=[UIColor clearColor];
if
(section==0) {
label.text=@
"個人好友"
;
}
else
label.text=@
"黑名單"
;
[view addSubview:label];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.tag=section;
//注意添加button的tag用於鑑別是哪一個button;
button.frame=CGRectMake(0, 0, 320, 30);
[button addTarget:self action:@selector(buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
return
view;
}
//button事件用於控制開關狀態;
-(
void
)buttonclick:(UIButton *)sender
{
if
(p[sender.tag]==0) {
p[sender.tag]=1;
}
else
p[sender.tag]=0;
[tableview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationFade];
//從新加載section根據button的不一樣來決定加載那個section 之 因此能夠這樣適應爲button。tag是根據section設置的;此時加載section須要的數據是nsindexset類型搜一要把button的tag轉換成此類型;
}
爲解決問題:怎麼讓section頭寬度變大?
解決方法:設置tableview的section的頭高 設置代碼爲:tableview.sectionHeaderHeight=30;
cell的層次 view在cell上contentview又在view上其餘控件又加在了content view上
cell的contentView cell上面的內容視圖
9.20週四
和xib文件連用建立表格
建立表格框,而後建立xib文件,並把xib文件中的默認視圖刪除;添加tableviewcell 能夠在裏面添加其餘控件;
-(
void
)viewDidLoad
{ [super viewDidLoad];
UITableView * tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320,460) style:UITableViewStylePlain];
tableView.delegate=self;
tableView.dataSource=self;
[self.view addSubview:tableView];
[tableView release];
}
//設置行數
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return
20;
}/
//在建立cell的函數中將xib建立的文件添加到tableview中;
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:indexPath.row%2==0?@
"ID"
:@
"ID2"
];
if
(cell==nil){
cell=[[[NSBundle mainBundle] loadNibNamed:indexPath.row%2==0?@
"MYcell"
:@
"MYCell2"
owner:self options:nil]objectAtIndex:0];
//和xib中的文件綁定;
}
//設置cell顏色要注意是設置contentview的顏色應爲它覆蓋在cell上;
return
cell;
}
//自定義的cell注意在建立自定義cell類在寫繼承時是繼承UITableViewCell;
建立cell類後在初始化文件中寫上初始化的cell特性,既須要更改什麼屬性,加在其餘控件;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if
(self) {
self.myLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
myLabel.textAlignment=UITextAlignmentCenter;
myLabel.backgroundColor=[UIColor greenColor];
[self addSubview:myLabel];
[myLabel release];
}
return
self;
}
//在控制器中建立cell時建立自定義cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell=(CustomCell *)[tableView dequeueReusableCellWithIdentifier:@
"ID"
];
if
(cell==nil) {
cell=[[CustomCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@
"ID"
];
}
//加載文本從資源文件中獲取;
NSString *str=[NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@
"ui"
ofType:@
"rtf"
] encoding:NSUTF8StringEncoding error:nil ];
cell.myLabel.text=str;
return
cell;
}
9.24 週一 第十一週(網絡
在使用不一樣的網絡協議傳輸時都要先加入協議文件;若是用到他們的對應函數時要寫協議,設置代理
1.json 格式網絡傳輸
在網絡中傳輸請求時用的時是字符串。他們用{}[]連接起來;其中{}表示字典;[]表示數組;解析時只要分清層次須要從哪取數據就用相應的數組或對象取數據;
1.網絡數據解析
NSString *json=@
"{\"title\":\"harry pottery\",\"price\":\"99999\"}"
;
NSDictionary *dic=[json JSONValue];
NSString *str=[dic objectForKey:@
"title"
];
NSLog(@
"%@"
,str);
json=@
"[\" a\", \"b\",\"c\"]"
;
NSArray *array=[json JSONValue];
for
(NSString *s in array) {
NSLog(@
"%@"
,s);
}
json=@
"{\"key1\":[{\"key2\":\"value2\"},\"value3\" ]}"
;
NSDictionary *dic1=[json JSONValue];
array=[dic1 objectForKey:@
"key1"
];
dic=[array objectAtIndex:0];
NSString *st=[dic objectForKey:@
"key2"
];
NSLog(@
"%@"
,st );
2 .SBJson網絡傳輸數據:要加入第三方協議:SBJson 冰島入SBJson.h頭文件
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@
"http://localhost/1.gif"
]];
UIImage *image=[UIImage imageWithData:data];
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
imageview.image=image;
[self.view addSubview:imageview];
3.SDWebImage 網絡傳輸
在使用圖片按鈕傳輸時要引人頭文件
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
NSURL *url=[NSURL URLWithString:@
"http://localhost/1.gif"
];
UIImageView *image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
[image setImageWithURL:url];
[self.view addSubview:image];
[image release];
4.ASIHTTPRequest網絡傳輸???????
首先要導人四個庫文件libz.1.2.5.dylib,CFNetwork.framework,
SystemConfiguration.framework,MobileCoreServices.framework
引人頭文件 #import
"ASIHTTPRequest.h"
同時要添加ASIHTTPRequest.h協議;設置代理
NSURL *url=[NSURL URLWithString:@
"http://localhost/1.gif"
];
ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
request.delegate=self;
[request startSynchronous];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
-(
void
)requestFinished:(ASIHTTPRequest *)request
{
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
imageview.image=[UIImage imageWithData:request.responseData];
[self.view addSubview:imageview];
}
5.異步傳輸 這種異步傳輸須要代理 <NSURLConnectionDataDelegate>
/異步傳輸數據:優勢:在傳輸數據沒有完成前,能夠對網頁上的其餘東西進行操做;
[super viewDidLoad];
NSURL *url=[NSURL URLWithString:@
"http://localhost/1.gif"
];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
data1=[[NSMutableData alloc]init];
imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
[self.view addSubview:imageview];
}
//連接響應時調用
-(
void
)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@
"didreceiveresponse"
);
}
//加載完成時調用
-(
void
)connectionDidFinishLoading:(NSURLConnection *)connection
{
imageview.image=[UIImage imageWithData:data1];
NSLog(@
"connectiondidFinishload"
);
}
-(
void
)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[data1 appendData:data];
NSLog(@
"didreceivedata"
);
}
//連接發生錯誤時響應;
-(
void
)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@
"error"
);
}
xml
首先導人GData 文件, 而後經過在項目頭文件中Build Phases中第三個選項中數添加libxml2 文件並將其移動到項目下面, 而後在 BuildSettings中在search paths中在 Header Search Paths 中添加路徑/use/include/libxml2 這樣就可用xml 讀取網絡文件了;
1.將網絡編碼文件存入字符串;
NSString *xmlstr=[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@
"xml"
ofType:@
"txt"
] encoding:NSUTF8StringEncoding error:nil];
2.將字符串轉變成GDataXMLDocument 類行的文件;
獲取文件
GDataXMLDocument *xmldoc=[[GDataXMLDocument alloc]initWithXMLString:xmlstr options:0 error:nil];
3.從文件中獲取根元素;
GDataXMLElement * rootEle=[xmldoc rootElement];
4.獲取元素的值
rootEle.stringValue
5.獲取根元素下面的某項值,用所在位置獲取;也能夠經過數組把他們全都放到數組,在從數組中獲取;
GDataXMLElement *sysele=(GDataXMLElement *)[rootEle childAtIndex:0];
GDataXMLElement cityele=[sysele childAtIndex:0];
NSArray *array=[sysele children];
6.獲取元素的 XMLString屬性值; 獲取屬性stringValue值 屬性名值name
array =[intel children];
for
(GDataXMLElement * itemele in array) {
for
(GDataXMLElement * item in itemele.attributes) {
NSLog(@
"%@"
,item.XMLString);
NSLog(@
"%@"
,item.stringValue);
NSLog(@
"%@"
,item.name);
}
}
7.經過元素名獲取元素;
GDataXMLElement *codeele=[[sysele elementsForName:@
"areaCode"
] objectAtIndex:0];
8.經過路徑獲取獲取元素;
GDataXMLElement *cityele=[[xmldoc nodesForXPath:@
"root/systemConfig/CityName"
error:nil] objectAtIndex:0];
NSLog(@
"%@"
,cityele.stringValue);
cityele=[[xmldoc nodesForXPath:@
"//CityName"
error:nil] objectAtIndex:0];
NSLog(@
"%@"
,cityele.stringValue);
NSArray *array=[xmldoc nodesForXPath:@
"//Item"
error:nil];
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[1]"
error:nil];
GDataXMLElement *tem =[[xmldoc nodesForXPath:@
"//Item"
error:nil] o bjectAtIndex:0];
GDataXMLElement *ele =[tem.attributes objectAtIndex:0];
NSLog(@
"%@"
,ele.stringValue);
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[last()]"
error:nil];
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[position()<3]"
error:nil];
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[position()<3]|// ****/item[2]"
error:nil];
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[@key=2]"
error:nil];
array=[xmldoc nodesForXPath:@
"//intentionLevel/Item[@key<3]"
error:nil];
在接收取出來的元素時,通常取出來的是數組,要用數組接,若是是單個元素要用數組的object 0去轉換成對象;而後再取其中的屬性;
網頁刷新
準備工做:
1.再刷新網頁時用到了第三方代理,在引入函數前要先添加文件
EGOTableViewPullRefresh
2。添加庫文件:QuartzCore.framework
3.加入代理:1.UITableViewDelegate,
2.UITableViewDataSource,
3.EGORefreshTableHeaderDelegate
viewdidload函數內容:
1.建立得到內容得數組;
dataArray=[[NSMutableArray alloc]initWithObjects:@
"a"
,@
"b"
,@
"c"
,@
"d"
,nil];
2.建立table 並設置代理;
table=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
table.delegate=self;
table.dataSource=self;
[self.view addSubview: table];
[table release];
3.建立刷新視圖
refreashview=[[EGORefreshTableHeaderView alloc]initWithFrame:CGRectMake(0, -460, 320, 460)];
refreashview.delegate=self;
4.添加刷新視圖到table中;
[table addSubview:refreashview];
[refreashview refreshLastUpdatedDate];
}
代理函數內容
加載時調用是table 它是個
bool
值,時時自動調用
-(
BOOL
)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
NSLog(@
"isloading"
);
return
isloading;
}
時間函數timer調用得方法
-(
void
)refresdata
{
[dataArray addObject:@
"new"
];
[table reloadData];
[refreashview egoRefreshScrollViewDataSourceDidFinishedLoading:table];
一但更新完之後就要把加載函數反回得
bool
值改變爲no便於下次加載;
isloading=NO;
}
//加載更新出發得更新函數;
-(
void
)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
isloading=YES;
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(refresdata) userInfo:nil repeats:NO];
NSLog(@
"didTrigger"
);
}
//屏幕滾動時調用
-(
void
)scrollViewDidScroll:(UIScrollView *)scrollView
{
// 調用這個函數用於調用加載函數並根據不一樣的狀態設置位置;
[refreashview egoRefreshScrollViewDidScroll:scrollView];
}
-(
void
)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(
BOOL
)decelerate
{ 根據如今更新的狀態,打開加載的控制器;
[refreashview egoRefreshScrollViewDidEndDragging:scrollView];
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
return
[NSDate date];
}
//建立tableview的基本函數;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return
dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@
"ID"
];
if
( cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@
"ID"
] autorelease];
}
cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];
return
cell;
}
-(
void
)dealloc
{
[dataArray release];
[super dealloc];
}
9.26 週三
數據庫操做;
進入數據庫
sqlite3 data.db
退出數據庫
.quit
建立表
create table Students(name, score);
插入數據前看是否有表,沒表就建立
create table
if
not exists Students(name,score);
插入數據
insert into Students values(
'kety'
,89);
刪除表
drop table Stufents
刪除某項數據
delete
from Students where name=
'hau'
;
修改數據
update Students set score=55 where name=
'hahan'
;
排序: 降序排; 默認升序排
select * from Book order by price desc;
排序後顯示前幾項
select * from Book order by price desc limit 5;
查詢某個條件範圍的所有數據
select * from Book where price>40;
查詢內容中的某一項
select name from Book;
兩個表關聯查詢
select Students.name, Student1.pro, Students.score from Students join Student1 on Students.name=Student1.name;
查詢紀錄數量;
select count(*)from Students;
前臺操做和數據庫連接
注意:在操做前要導入文件libsqlite3.dylib 導入頭文件#import
"sqlite3.h"
;
self.PATH=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@
"data.db"
];
注意: PATH 是接收路徑的字符串變量,注意前面要加上self;
在出發事件中進行後臺操做;
增長紀錄
-(
void
)add
{
sqlite3 *sql;
int
res =sqlite3_open([PATH UTF8String], &sql);
if
(res!=SQLITE_OK) {
NSLog(@
"open error"
);
return
;
}
NSString *sqlStr=@
"create table if not exists Students(name,score)"
;
res=sqlite3_exec(sql, [sqlStr UTF8String], NULL, NULL, NULL);
if
(res!=SQLITE_OK) {
NSLog(@
"Create error"
);
sqlite3_close(sql);
return
;
}
sqlStr =[NSString stringWithFormat:@
"insert into Students values('%@','%@')"
,namefield.text,scorefield.text];
res=sqlite3_exec(sql, [sqlStr UTF8String], NULL, NULL, NULL);
if
(res!=SQLITE_OK) {
NSLog(@
"insert error"
);
}
sqlite3_close(sql);
}
刪除紀錄
-(
void
)del
{
sqlite3 *sql;
int
res =sqlite3_open([PATH UTF8String], &sql);
if
(res!=SQLITE_OK) {
NSLog(@
"open error"
);
return
;
}
NSString *sqlStr=[NSString stringWithFormat:@
"delete from Students where name='%@'"
,namefield.text];
res=sqlite3_exec(sql, [sqlStr UTF8String], NULL, NULL, NULL);
if
(res!=SQLITE_OK) {
NSLog(@
"delete error"
);
}
sqlite3_close(sql);
}
更新紀錄
-(
void
)upd
{
sqlite3 * sql;
int
res =sqlite3_open([PATH UTF8String],&sql );
if
(res!=SQLITE_OK) {
NSLog(@
"open error"
);
return
;
}
NSString *sqlStr=[NSString stringWithFormat:@
"update Students set score='%@' where name='%@'"
,scorefield.text,namefield.text];
res=sqlite3_exec(sql, [sqlStr UTF8String], NULL, NULL, NULL);
if
(res!=SQLITE_OK) {
NSLog(@
"UPDATE ERROR"
);
return
;
}
sqlite3_close(sql);
}
查詢紀錄
-(
void
)sel
{
sqlite3 *sql;
int
res=sqlite3_open([PATH UTF8String], &sql);
if
(res!=SQLITE_OK) {
NSLog(@
"open error"
);
return
;
}
建立預處理
sqlite3_stmt *stmt;
NSString *sqlStr=@
"select *from Students"
;
res=sqlite3_prepare_v2(sql, [sqlStr UTF8String], -1, &stmt, NULL);
if
(res!=SQLITE_OK) {
NSLog(@
"prepare error"
);
return
;
}
while
(sqlite3_step(stmt)==SQLITE_ROW) {
char
*name=(
char
*)sqlite3_column_text(stmt, 0);
char
*score=(
char
*)sqlite3_column_text(stmt, 1);
NSLog(@
"%s %s"
,name,score);
}
sqlite3_close(sql);
}
建立新的線程:做用在主線程執行時同時調用另外一個線程使不一樣操做同時執行;用於網絡和數據庫傳送數據時不影響執行其餘內容
建立新線程:
[NSThread detachNewThreadSelector:@selector(
thread
) toTarget:self withObject:nil];
想要在新線程中執行的內容能夠能夠寫到新線程調用的函數中
-(
void
)
thread
{
[self performSelectorOnMainThread:@selector(main1) withObject:nil waitUntilDone:nil];
}
計時器也能夠開闢新線程;因此在網絡和數據庫傳輸數據時能夠用計時器來替代進程
[NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(timer) userInfo:nil repeats:YES];
在數據庫操做時添加,刪除,更新的操做思想:
1.打開數據庫;
2.建立操做語句;
3.執行語句;
4.關閉數據庫;
9.27 週四
引入第三方協議和後臺數據庫連接;
1.先引入數據庫文件libsqlite3.dylib 再添加第三方文件FMDB, 引入頭文件
#import "FMDatabase.h"
2.實現增,刪,改,查功能
-(
void
)add
{
FMDatabase *db=[FMDatabase databaseWithPath:PATH];
BOOL
res =[db open];
if
(res==NO) {
NSLog(@
"open error"
);
return
;
}
res=[db executeUpdate:@
"create table if not exists Students (name,score)"
];
if
(res==NO) {
NSLog(@
"creat error"
);
[db close];
return
;
}
res=[db executeUpdate:@
"insert into Students values(?,?)"
,namefield.text,scorefield.text];
if
(res==NO) {
NSLog(@
"insert error"
);
}
[db close];
}
-(
void
)del
{
FMDatabase *db=[FMDatabase databaseWithPath:PATH];
BOOL
res =[db open];
if
(res==NO) {
NSLog(@
"open error"
);
return
;
}
res=[db executeUpdate:@
"delete from Students where name =?"
,namefield.text];
if
(res==NO) {
NSLog(@
"delete error"
);
}
[db close];
}
-(
void
)upd
{
FMDatabase *db=[FMDatabase databaseWithPath:PATH];
BOOL
res=[db open];
if
(res==NO) {
NSLog(@
"open error"
);
return
;
}
res=[db executeUpdate:@
"update set score=77 from Students where name=?"
,namefield.text];
if
(res==NO) {
NSLog(@
"update error"
);
}
[db close];
}
-(
void
)sel
{
FMDatabase *db=[FMDatabase databaseWithPath:PATH];
BOOL
res=[db open];
if
(res==NO) {
NSLog(@
"open error"
);
return
;
}
預處理數據
FMResultSet *set=[db executeQuery:@
"select * from Students"
];
遍歷數據
while
([set next]) {
NSString *name=[set stringForColumn:@
"name"
];
NSString *score=[set stringForColumnIndex:1];
NSLog(@
"%@ %@"
,name ,score);
}
若是圖片通過編碼轉換成data類型存入數據庫取出來的方式以下;
1.從預處理中取出圖片的二進制編碼
NSData *data=[set objectForColumnIndex:1];
2.建立存放圖片的控件;
UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(50, 300, 100, 100)];
3.將數據轉換成image添加到控件中;
image.image=[UIImage imageWithData:data];
[self.view addSubview:image];
[db close];
}
sdafggfdhfjgsdfhgjfgkhljkgjfhgfdsaDFGH
其餘類型數據存入數據庫
在數據庫存儲中,能夠存儲nsstring,nsnumber ,nsdata ;若是想儲存其餘類型的數字須要將其內容都轉換成nsdata類型;
將image轉換成data類型;而後經過獲取data再將其轉換成image類型:
1.建立image
UIImage *image= [UIImage imageNamed:@
"5.png"
];
2.建立data用於存入數據;
NSMutableData *data=[NSMutableData dataWithCapacity:0];
3.建立編碼器
NSKeyedArchiver *arch= [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
4.編碼圖片;
[arch encodeObject:image forKey:@
"image"
];
5.完成編碼
[arch finishEncoding];
6.釋放;
[arch release];
7.建立解碼器
NSKeyedUnarchiver *unaarev=[[NSKeyedUnarchiver alloc]initForReadingWithData:data];
8.解碼圖片;
UIImage *image1=[unaarev decodeObjectForKey:@
"image"
];
9.解碼完成
[unaarev finishDecoding];
10.釋放
[unaarev release];
11.展現圖片
UIImageView * image2=[[UIImageView alloc]initWithFrame:CGRectMake(30, 300, 100, 100)];;
image2.image=image1;
[self.view addSubview:image2];
聊天對話框的的氣泡拉伸思想: 爲了達到不矢真,橫向延伸要用用豎向的一條像素按所需長度複製;豎向延伸要拿橫向的一條像素按所需長度延伸;
具體實現:
1.建立氣泡
image =[UIImage imageNamed:@
"5.png"
]
cap:帽子擴展延伸;
2。拉伸氣泡函數
image=[image stretchableImageWithLeftCapWidth:14 topCapHeight:14];
image2.image=image;
NSString *str=@
"abcdet"
;
CGSize size=[str sizeWithFont:[UIFont systemFontOfSize:12.0] constrainedToSize:CGSizeMake(200, 1000) lineBreakMode:UILineBreakModeWordWrap];
10.8 週一
向服務器上傳數據
1.先添加第三方文件ASIHTTPRequst 導人第三方文件:#import
"ASIFormDataRequest.h"
而後添加四個數據庫文件 libz.1.2.5.dylib ,MobileCoreServices.framework, Systemconfiguration.framework;, CFNetwork.framework
2. 實現上傳:
1.建立與服務器連接對象;
NSURL *url=[NSURL URLWithString:@
"http://169.254.59.31/pk.php"
];
2.建立向服務器發出請求的對象;
ASIFormDataRequest *asiform=[ASIFormDataRequest requestWithURL:url];
3.設置上傳內容:上傳內容能夠是文件,也能夠是二進制數據
一種函數 [asiform setFile:[[NSBundle mainBundle]pathForResource:@
"5"
ofType:@
"jpg"
] forKey:@
"image"
];
第二種函數:[asiform setFile:[[NSBundle mainBundle]pathForResource:@
"5"
ofType:@
"jpg"
] withFileName:@
"2.png"
andContentType:@
"image/jpg"
forKey:@
"image"
];
不一樣點:第二種會在服務器端顯示你所設置的文件名,若是是二進制數據後者會顯示類型,若是是圖片會顯示圖片的縮略圖,若是用第一種不能顯示其縮略圖;
4.設置代理,這樣就可使用其函數了;包括上傳成功失敗的函數
5.最後讓其上傳執行
[asiform startSynchronous];
-(
void
)viewDidLoad
{
[super viewDidLoad];
NSURL *url=[NSURL URLWithString:@
"http://169.254.59.31/pk.php"
];
ASIFormDataRequest *asiform=[ASIFormDataRequest requestWithURL:url];
1. [asiform setFile:[[NSBundle mainBundle]pathForResource:@
"5"
ofType:@
"jpg"
] forKey:@
"image"
];
2. [asiform setFile:[[NSBundle mainBundle]pathForResource:@
"5"
ofType:@
"jpg"
] withFileName:@
"2.png"
andContentType:@
"image/jpg"
forKey:@
"image"
];
NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@
"5"
ofType:@
"jpg"
]];
[asiform setData:data forKey:@
"image"
];
[asiform setData:data withFileName:@
"5.jpg"
andContentType:@
"image/jpg"
forKey:@
"image"
];
asiform.delegate=self;
[asiform startSynchronous];
}
-(
void
)requestFailed:(ASIHTTPRequest *)request
{
NSLog(@
"error"
);
}
-(
void
)requestFinished:(ASIHTTPRequest *)request
{
NSLog(@
"ok"
);
}
10.9週二
mp3播放器製做
1.加載庫文件 AVFoundation.framework和QuartzCore.framework;( 沒弄明白這個文件的做用,由於加不加他沒什麼做用)而後引入頭文件
#import <AVFoundation/AVFoundation.h>
#import <QuartzCore/QuartzCore.h>
2.mp3實現代碼
-(
void
)viewDidLoad
{
[super viewDidLoad];
//建立播放按鈕,並分別爲添加事件
UIButton *play=[UIButton buttonWithType:UIButtonTypeRoundedRect];
play.frame=CGRectMake(20, 100, 80, 30);
[play addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside ];
[play setTitle:@
"play"
forState:UIControlStateNormal];
[self.view addSubview:play];
UIButton *pause=[UIButton buttonWithType:UIButtonTypeRoundedRect];
pause.frame=CGRectMake(120, 100, 80, 30);
[pause setTitle:@
"pause"
forState:UIControlStateNormal];
[pause addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pause];
UIButton *stop=[UIButton buttonWithType:UIButtonTypeRoundedRect];
stop.frame=CGRectMake(220, 100, 80, 30);
[stop addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
[stop setTitle:@
"stop"
forState:UIControlStateNormal];
[self.view addSubview:stop];
//建立數據連接
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@
"withyou"
ofType:@
"mp3"
]];
player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
[player prepareToPlay];
//建立滑條用於控制音量,聲道和播放速率
UISlider *volslider=[[UISlider alloc]initWithFrame:CGRectMake(50, 50, 200, 0)];
volslider.minimumValue=0.0;
volslider.maximumValue=1.0;
volslider.minimumValue=-1.0;
volslider.minimumValue=1.0;
player.enableRate=YES;
volslider.minimumValue=0.5;
volslider.maximumValue=2.0;
volslider.value=1.0;
//爲滑條添加滑動事件,注意出發事件是滑條值改便時;
[volslider addTarget:self action:@selector(volslider:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:volslider];
[volslider release];
//建立進度條,控制音頻播放進度
UISlider *proslider=[[UISlider alloc]initWithFrame:CGRectMake(50, 20, 220, 0)];
//設置進度條最大最小播放百分比
proslider.minimumValue=0.0;
proslider.maximumValue=1.0;
proslider.value=0.0;
proslider.tag=100;
[proslider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:proslider];
[proslider release];
//e ,j 是防止暫停,中止點擊超過一次時屢次釋放timer致使崩潰
e=1;
j=1;
//設置代理
player.delegate=self;
//設置音頻頻率顯示條
for
(
int
i=0; i<4; i++) {
pro[i]=[[UIProgressView alloc]initWithFrame:CGRectMake(50*i, 440, 200, 0)];
[self.view addSubview:pro[i]];
[pro[i] release];
//旋轉進度條,由於要的是弧度因此參數要改變成弧度制
pro[i].transform=CGAffineTransformMakeRotation(270 *M_PI/180);
pro[i].layer.anchorPoint=CGPointMake(0.0, 0.0);
}
player.meteringEnabled=YES;
}
-(
void
)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(
BOOL
)flag
{
NSLog(@
"success"
);
}
//進度條隨音頻改變
-(
void
)progressSlider:(UISlider *)slider
{
player.currentTime=player.duration*slider.value;
}
-(
void
)volslider:(UISlider *)slider
{
player.volume=slider.value;
player.pan=slider.value;
player.rate=slider.value;
}
//時間控制器調用的函數
-(
void
)refresh
{
UISlider *proslider=(UISlider *)[self.view viewWithTag:100];
proslider.value=player.currentTime/player.duration;
[player updateMeters];
pro[0].progress=[player peakPowerForChannel:0]/-100;
pro[1].progress=[player peakPowerForChannel:1]/-100;
pro[2].progress=[player averagePowerForChannel:0]/-100;
pro[3].progress=[player averagePowerForChannel:1]/-100;
}
//播放控制 用添加時間器來控制
-(
void
)play
{
[player play];
timer=[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(refresh) userInfo:nil repeats:YES];
e=1;
j=1;
}
//中止控制 注意e,j是分別用於控制中止按鈕,暫停時間器釋放,避免時間器重複釋放致使的崩潰;
-(
void
)stop
{
if
(e==1&&j==1) {
[player stop];
[timer invalidate];
//若是按中止鍵,控制進度條也中止
UISlider *proslider=(UISlider *)[self.view viewWithTag:100];
player.currentTime=0.0;
proslider.value=player.currentTime;
e=0;
j=0;
}
else
if
(e==1&&j==0)
{
UISlider *proslider=(UISlider *)[self.view viewWithTag:100];
player.currentTime=0.0;
proslider.value=player.currentTime;
e=0;
}
}
//控制暫停
-(
void
)pause
{
if
(j==1&&e==1) {
[player pause];
[timer invalidate];
j=0;
}
}
-(
void
)dealloc
{
[player release];
[super dealloc];
}
mp4播放器
1.導人庫文件 MeduaPlayer.framework. 並導人頭文件#import <MediaPlayer/MediaPlayer.h>
2. 代碼實現解析
-(
void
)viewDidLoad
{
//建立按鈕用於播放控制
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(120, 400, 70, 40);
[button addTarget:self action:@selector(buttonclick) forControlEvents:UIControlEventTouchUpInside];
//注意播放控制器又兩種一種是播放控制器,MPMoviePlayerController 一種是帶view的播放控制器;MPMoviePlayerViewController 兩者的不一樣之處是前者要播放時是將其視圖加入主控制視圖中[self.view addSubview:play.view];,播放是調用播放函數[play play];後者是將播放控制交給MPMoviePlayerViewController:[self presentModalViewController:play animated:YES]; 這樣一開始播放會全屏播放;
//初始化MPMoviePlayerViewControlle,資源是當前文件
play1=[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@
"4"
ofType:@
"mp4"
]]];
//初始化MPMoviePlayerController 資源是當前文件
play=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@
"4"
ofType:@
"mp4"
]]];
//設置播放器的 frame屬性
play.view.frame=CGRectMake(0, 0, 320, 300);
//設置播放器背景色,雖然能設置,可是不支持使用此屬性;
play.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@
"1.bmp"
]];
//播放器的控制屬性,用於控制播放模式默認使嵌入模式;
play.controlStyle=MPMovieControlStyleEmbedded;
//播放重複模式,能夠用於設置重複播放;
play.repeatMode=MPMovieRepeatModeOne;
[self.view addSubview:play.view];
[self.view addSubview:button];
}
//控制播放器播放;
-(
void
)buttonclick
{
[self presentModalViewController:play animated:YES];
[play play];
}
10.11週四 畫圖
1.畫圖工具要新建一個uiview文件 而後在這個文件的.m文件中的- (
void
)drawRect:(CGRect)rect函數中畫圖
2.畫各中圖的方法
UIImage* image = [UIImage imageNamed:@
"5.png"
];
[image drawInRect:CGRectMake(100, 100, 100, 100)];
NSString* str = @
"ABC"
;
[str drawInRect:CGRectMake(100, 100, 100, 50) withFont:[UIFont systemFontOfSize:30.0] lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];
建立畫紙
CGContextRef
ref
= UIGraphicsGetCurrentContext();
畫起點:
CGContextMoveToPoint(
ref
, 20, 100);
添加點
CGContextAddLineToPoint(
ref
, 300, 100);
CGContextAddLineToPoint(
ref
, 150, 300);
封閉圖形
CGContextClosePath(
ref
);
CGContextSetStrokeColorWithColor(
ref
, [UIColor blueColor].CGColor);
畫路徑 結束畫圖
CGContextStrokePath(
ref
);
CGContextSetLineWidth(
ref
, 20.0);
float
length[] = {40,20,40};
CGContextSetLineDash(
ref
, 0, length, 2);
參數三是用於實線和間隔循環的數組;
參數四是用於要去數組的前幾個數循環;
CGContextSetLineCap(
ref
, kCGLineCapSquare);
//線段鏈接處的鏈接樣式
CGContextSetLineJoin(
ref
, kCGLineJoinRound);
CGContextStrokePath(
ref
);
CGContextRef
ref
= UIGraphicsGetCurrentContext();
//設置矩形的fram
CGContextAddRect(
ref
, CGRectMake(100, 100, 200, 100));
//設置線寬
CGContextSetLineWidth(
ref
, 10.0);
//設施線的顏色
CGContextSetStrokeColorWithColor(
ref
, [UIColor greenColor].CGColor);
//設置填充色;
CGContextSetFillColorWithColor(
ref
, [UIColor blueColor].CGColor);
//注意下面的三個生成圖像的方法的不一樣點
1.第一個只畫輪廓
2.只填充圖像的內部,不現實邊框
3.邊框和填充都顯示,注意後面的參數式fill和stroke都有的,通常fill是內部填充的屬性,而stroke是線的屬性
CGContextDrawPath(
ref
, kCGPathFillStroke);
CGContextRef
ref
= UIGraphicsGetCurrentContext();
設置圓的框架大小
CGContextAddEllipseInRect(
ref
, CGRectMake(100, 100, 200, 100));
CGContextStrokePath(
ref
);
CGContextRef
ref
= UIGraphicsGetCurrentContext();
畫自由圓
設置圓心位置
CGContextMoveToPoint(
ref
, 150, 150);
畫圓,第二,三個 是圓心位置,第四個參數是半徑 第五,六個參數數是開始和結束的角,角是弧度制,最後一個參數是順時針和逆時針旋轉1表示順時針,而表示逆時針
CGContextAddArc(
ref
, 150, 150, 100, 0, 270 * M_PI / 180, 1);
設置圖形填充色
CGContextSetFillColorWithColor(
ref
, [UIColor purpleColor].CGColor);
填充圖形;
CGContextFillPath(
ref
);
從新設置圓點 ,至關於在新的圖層上畫圖,這樣能夠爲每一個圖形設置不一樣的顏色;
CGContextMoveToPoint(
ref
, 150, 150);
CGContextAddArc(
ref
, 150, 150, 100, 0, 120 * M_PI / 180, 0);
CGContextSetFillColorWithColor(
ref
, [UIColor orangeColor].CGColor);
CGContextFillPath(
ref
);
CGContextMoveToPoint(
ref
, 150, 150);
CGContextAddArc(
ref
, 150, 150, 100, 120 * M_PI / 180, 270 * M_PI / 180, 0);
CGContextSetFillColorWithColor(
ref
, [UIColor blueColor].CGColor);
CGContextFillPath(
ref
);
//畫曲線
CGContextRef
ref
= UIGraphicsGetCurrentContext();
設置初試點
CGContextMoveToPoint(
ref
, 20, 400);
畫曲線 第二,三個參數是曲線始末兩點切線的焦點座標;後兩個參數是末點的座標;
CGContextAddQuadCurveToPoint(
ref
, 0, 100, 300, 400);
CGContextStrokePath(
ref
);
//設置圖形的透明度和陰影
CGContextRef
ref
= UIGraphicsGetCurrentContext();
CGContextAddRect(
ref
, CGRectMake(100, 100, 150, 150));
CGContextSetLineWidth(
ref
, 10.0);
CGContextSetStrokeColorWithColor(
ref
, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(
ref
, [UIColor redColor].CGColor);
//設置圖形的透明度
CGContextSetAlpha(
ref
, 0.5);
//設置圖形陰影 第二個參數是陰影向又向下的偏移量 ,最後一個參數是羽化程度
CGContextSetShadow(
ref
, CGSizeMake(20, 20), 10);
CGContextDrawPath(
ref
, kCGPathFillStroke);
動畫效果總結
1.之前給uiview 添加動畫效果;
設置動畫的方向
設置動畫各階段的調用的函數;
CATransition 用時要導人庫文件QuartzCore.framework 在加入頭文件#import <QuartzCore/QuartzCore.h>
初始化
CATransition *trans=[CATransition animation];
設置動畫時間;
trans.duration=1.0;
設置動畫進入曲線
trans.timingFunction=UIViewAnimationCurveEaseInOut;
設置動畫的類型 類型能夠直接用字符串;類型爲:
1. 1. pageCurl 向上翻一頁
2. pageUnCurl 向下翻一頁
3. rippleEffect 滴水效果
4. suckEffect 收縮效果,如一塊布被抽走
5. cube 立方體效果
6. oglFlip 上下翻轉效果
trans.type=@
"rippleEffect"
;
動畫進入類型
trans.subtype=kCATransitionFromTop;
設置次動畫;
設置動畫代理
trans.delegate=self;
[self.view.layer addAnimation:trans forKey:nil];
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}
-(
void
)animationDidStart:(CAAnimation *)anim
{
NSLog(@
"strat"
);
}
-(
void
)animationDidStop:(CAAnimation *)anim finished:(
BOOL
)flag
{
NSLog(@
"stop %d"
,flag);
}
注:CATransition動畫只能在圖層上加,因此要切換頁view時也要加到view.layer上;如在切換控制器時作法self.navigationController.view.layer addAnimation:tran forKey:nil];
[self.navigationController pushViewController:rvc animated:NO];
其中animated的yes或no不要緊;
10.12日 地圖
1.建立地圖須要添加庫文件:CoreLocation.framework
MapKit.framework
而後添加建立頭文件地圖類#import <MapKit/MapKit.h>
由於用到了類的代理函數需添加協議 <CLLocationManagerDelegate,MKMapViewDelegate>
2.代碼實線
建立兩個類 MKMapView *map;
CLLocationManager *localmanager;
-(
void
)viewDidLoad
{
//建立地圖
map=[[MKMapView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:map];
CLLocationCoordinate2D coordinate=CLLocationCoordinate2DMake(40.035731, 116.351008);
MKCoordinateSpan span=MKCoordinateSpanMake(0.5, 0.5);
將經緯度和顯示比例添加到 原始方位中,當打開地圖時地圖上顯示此位置;
MKCoordinateRegion region=MKCoordinateRegionMake(coordinate, span);
map.region=region;
//設置地圖的顯示類型,衛星圖,普通地圖,修改過的衛星圖;
//設置map代理
map.delegate=self;
//建立位置管理對象;
localmanager=[[CLLocationManager alloc]init];
localmanager.desiredAccuracy=kCLLocationAccuracyBest;
localmanager.distanceFilter=100;
[localmanager startUpdatingLocation];
localmanager.delegate=self;
實線代理類中的函數
//設置標題
-(NSString *)title
{
return
@
"標題"
;
}
//設置副標題
-(NSString *)subtitle
{
return
@
"副標題"
;
}
//設置將大頭針插到的位置;
-(CLLocationCoordinate2D)coordinate
{
CLLocationCoordinate2D cooridinate=CLLocationCoordinate2DMake(40.035731, 116.351008);
return
cooridinate;
}
爲了能多插入幾個大頭針能夠更改他們的屬性,位置,咱們能夠建立一個初始化函數,經過建立不一樣的對象,實現多大頭針;
-(id)initWithTitle:(NSString *)title subTitle:(NSString *)subtitle coordinate:(CLLocationCoordinate2D)coordinate
{
self=[super init];
if
(self) {
_title=title;
_subtitle=subtitle;
_coordinate=coordinate;
這三個參數都是自定義屬性;在返回函數中能夠直接分別返回這幾個屬性
}
return
self;
}
回到根控制文件建立大頭針,用自定義初始化函數初始化大頭針;
MyAnnotion *myann=[[MyAnnotion alloc]initWithTitle:@
"標題"
subTitle:@
"副標題"
coordinate:coordinate];
給地圖添加大頭針
[map addAnnotation:myann];
建立一個長壓手勢,在手勢函數中
UILongPressGestureRecognizer *press=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
給地圖添加手勢
[map addGestureRecognizer:press];
[map release];
}
長按觸發的手勢函數;
-(
void
)longpress:(UILongPressGestureRecognizer *)press
{
爲了防治一直按鍵不斷的產生大頭針 要對按鍵狀態進行判斷,只有第一次長按才添加大頭針
if
(press.state==UIGestureRecognizerStateBegan) {
CGPoint piont=[press locationInView:self.view ];
CLLocationCoordinate2D coordinate=[map convertPoint:piont toCoordinateFromView:map];
MyAnnotion * annontion=[[MyAnnotion alloc]initWithTitle:@
"title"
subTitle:@
"subtite"
coordinate:coordinate];
//爲大頭針出現時添加動做;
[map addAnnotation:annontion];
}
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *pinView=(MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@
"ID"
];
if
([annotation isKindOfClass:[mapView.userLocation
class
]]) {
return
nil;
}
if
(pinView ==nil){
//建立大頭針使用咱們定義加入地圖的大頭針;
pinView=[[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@
"ID"
]autorelease];
}
pinView.canShowCallout=YES;
pinView.animatesDrop=YES;
//設置針頭顏色
pinView.pinColor=MKPinAnnotationColorPurple;
建立視圖用於添加到大頭針細節視圖中
UIView *leftview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
leftview.backgroundColor=[UIColor greenColor];
pinView.leftCalloutAccessoryView=leftview;
UIButton *button=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView=button;
return
pinView;
}
//定位函數
-(
void
)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
把用戶的位置屬性設爲yes來展現用戶的位置;
map.showsUserLocation=YES;
設置顯示比例
MKCoordinateSpan span=MKCoordinateSpanMake(0.5, 0.5);
建立原始位置屬性,此時經緯能夠用函數的參數來設置,當前所處的位置;
MKCoordinateRegion region=MKCoordinateRegionMake(newLocation.coordinate, span);
動畫添加位置
[map setRegion:region animated:YES];
更新位置
[localmanager startUpdatingLocation];
}
遊戲開發
cocos2d oc
cocos2d-x( 中國人維護 不如cocos2d多) 2d-x c++
cocos2d-android java
cocos2d-html5
cocos2d-flash
cocos2d流程:和電影流程差很少
遊戲開始:
1。初始化
libs:遊戲引擎;
加庫:opencles.framework(計算機圖形學)
注:gpu:是數
注意:選擇白庫時選最短得
plist圖片要和png圖片名稱相同
注:在遊戲當中必定要注意產生對象的釋放;由於內容比較多,如不釋放內存泄漏很是嚴重;
遊戲一:發射打擊;
1。加載所需文件: openal.framework ,openGLES.framework,quartacore.framework,audiotoolbox.faramework,avfoundation.framwork,libz.dylib;
添加libs文件cocos2d包,再加上所需圖片和音樂;
2.遊戲界面只有一個導演,一個舞臺,每一個界面至關於一個節目;界面切換靠的是導演指導哪一個節目上場;每一個節目上要添加層靠曾來展現內容;
具體操做是:
1.建立導演,並判斷是否能運行最新的導演
BOOL
ret = [CCDirector setDirectorType:kCCDirectorTypeDisplayLink];
//這是功能比較強大的導演;
if
(ret == FALSE) {
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
//建立導演,他是個共享函數,程序始終只有一個導演;
這個導演適於全部版本的系統;
2.建立舞臺
CGRect rect = self.window.bounds;//獲得舞臺的尺寸
建立舞臺view
EAGLView *glView = [[EAGLView alloc] initWithFrame:rect]
3. 導演讓屏幕橫屏
[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
4. 關聯導演和glview
[director setOpenGLView:glView];
5. 設置遊戲刷新率
[director setAnimationInterval:1/60.0f];
6.把舞臺添加到窗口
[self.window addSubview:glView];
[glView release];
7.運行第一個節目
CCScene *s = [StartLayer scene];
調用start layer的類函數用於切換節目 [StartLayer scene] 的類函數要些在StartLayer中方便使用
[director runWithScene:s];
讓導演運行第一個節目;
在運行一個節目時須要注意的點:
1。建立切換節目的類函數;
+ (id) scene {
CCScene *s = [CCScene node];
CCLayer *l = [StartLayer node];
[s addChild:l];
return
s;
}
node函數是繼承node的 初始化函數是[[[self alloc] init] autorelease];用這個函數比較簡便;可是初始化時若是對象就以兩個能夠這樣初始化;若是對象不少就不要這樣初始化;由於自動釋放時間不肯定容易佔用內存;
2.初始化層;
注:一開始加載的東西要放在初始化中;
建立菜單
CCMenuItemFont *startItem = [[CCMenuItemFont alloc] initFromString:@
"開始遊戲"
target:self selector:@selector(beginGame)];
CCMenuItemFont是文字菜單項;有圖片菜單項,文本項等等
點擊菜單項都會出發事件;點擊開始遊戲菜單項就要出發新節目;在出發函數中要
CCMenuItem *helpItem = [[CCMenuItemFont alloc] initFromString:@
"幫助"
target:self selector:@selector(helpGame)];
CCMenu *menu = [CCMenu menuWithItems:startItem, helpItem, nil];
建立菜單,同時加入菜單項;
[menu alignItemsVertically];
[self addChild:menu];
點擊菜單項都會出發事件;點擊開始遊戲菜單項就要出發新節目;在觸發函數中要要切換節目
2.建立新節目:
CCScene *s = [LoadingLayer scene];//這個函數一樣是類函數,
CCDirector *d = [CCDirector sharedDirector];獲取導演;
[d replaceScene:s];
讓新節目代替舊節目; 這個函數的好處是把舊節目釋放;再也不佔用內存
登錄節目:
節目一樣要些建立節目的類函數,和上面的寫法同樣
登錄時顯示的是一個進度條;經過擴大其中一個進度條的長度來模仿數據加載;
初始化函數:
在cocos2d中的精靈至關於ui中的圖片
CCSprite *redSprite = [[CCSprite alloc] initWithFile:@
"progressbar1.png"
];
CCDirector *d = [CCDirector sharedDirector];
CGSize winSize = [d winSize];
設置錨點;錨點至關於圖片的基準點;
redSprite.anchorPoint = ccp(0, 0);
CGSize redSpriteSize = [redSprite contentSize];
CGFloat x = (winSize.width-redSpriteSize.width)/2.0f;
CGFloat y = (winSize.height-redSpriteSize.height)/2.0f;
設置精靈的位置;
redSprite.position = ccp(x, y);
將精靈添加到圖層;
[self addChild:redSprite];
[redSprite release];
注意局部對象及時的銷燬;
yellowSprite = [[CCSprite alloc] initWithFile:@
"progressbar2.png"
];
yellowSprite.anchorPoint = ccp(0, 0);
yellowSprite.position = ccp(x, y);
//scale是縮放的意思;能夠對總體縮放,也能夠縮放x和y;
yellowSprite.scaleX = 0.2f;
yellowSprite.tag = 100;
[self addChild:yellowSprite];
//圖層也能夠添加計時器;不用再建立timer;
[self schedule:@selector(timer:) interval:0.5f];
每隔0。5秒調用的函數;
- (
void
) timer:(
double
)dt {
CGFloat scalex = [yellowSprite scaleX];
scalex += 0.1f;
[yellowSprite setScaleX:scalex];
if
(scalex >= 1.0f) {
[self unschedule:@selector(timer:)];
[[CCDirector sharedDirector] replaceScene:[GameLayer scene]];
}
}
遊戲界面
遊戲界面一樣是經過類函數建立節目;在初始化函數種須要作的工做是加載背景圖,和遊戲者。建立隨時間調用的函數;
CCSprite *bgSprite = [[CCSprite alloc] initWithFile:@
"bg.png"
];
bgSprite.anchorPoint = ccp(0, 0);
bgSprite.position = ccp(0, 0);
[self addChild:bgSprite];
[bgSprite release];
CCSprite *player = [[CCSprite alloc] initWithFile:@
"Player.png"
];
CGSize playerSize = [player contentSize];
CGSize winSize = [[CCDirector sharedDirector] winSize];
player.position = ccp(playerSize.width/2.0f, winSize.height/2.0f);
[self addChild:player];
[player release];
tagetarray=[[CCArray alloc]init];
bulletarray=[[CCArray alloc]init];
[self addTarget];
[self schedule:@selector(targetTimer:) interval:1.0f];
[self schedule:@selector(gameLogic)];
self.isTouchEnabled = YES;
發子彈須要觸摸因此要讓屏幕可觸摸;
建立打擊目標調用的函數;
-(
void
)addTarget
{ 建立精靈;
CCSprite * taget=[[CCSprite alloc]initWithFile:@
"Target.png"
];
將精靈添加到數組;用於測試是否被子彈打中;
[tagetarray addObject:taget];
CGSize winsize=[[CCDirector sharedDirector] winSize];
CGSize tagetsize=[taget contentSize];
經過隨機數獲設置精靈的隨機高度;注:隨機數很大經過取餘來控制隨機數的範圍;
CGFloat y= tagetsize.height/2.0f+ arc4random()%(
int
)(winsize.height-tagetsize.height);
CGFloat x=winsize.width;
taget.position=ccp(x,y);
[self addChild:taget];
[taget release];
CGPoint dispoint=ccp(0, y);
設置動做點,精靈會在設置的時間內從起點運動到目地點;
CCMoveTo *move=[[CCMoveTo alloc]initWithDuration:2 position:dispoint];
CGPoint destpoint2=ccp(300,0 );
動做點可設置跳躍點
CCJumpTo *move2=[[CCJumpTo alloc]initWithDuration:2 position:destpoint2 height:200 jumps:1];
用來調用某個函數;通常是用來作善後工做;
CCCallFuncN *finish= [[CCCallFuncN alloc]initWithTarget:self selector:@selector(finish:)];
建立隊列,調用者會按隊列順序執行;
CCSequence *squence=[CCSequence actions:move,move2,finish, nil];
讓對象按隊列運行;
[taget runAction:squence];
[move2 release];
[move release];
}
觸摸函數用於添加子彈;注意觸摸函數的寫法;函數touch後帶es的和ui的觸摸函數同樣
-(
void
)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
建立音樂引擎;
[[SimpleAudioEngine sharedEngine] playEffect:@
"pew-pew-lei.caf"
];
CCSprite *bulletsprite=[[CCSprite alloc]initWithFile:@
"Bullet.png"
];
bulletsprite.tag=10;
建立觸摸對象
UITouch *onetouch=[touches anyObject];
獲取觸摸對象的位置;
CGPoint touchpoint=[onetouch locationInView:onetouch.view ];
//注意獲取的觸摸點時豎屏時的因此得把該點轉換成遊戲橫屏時的觸摸點;
CGPoint glpoint=[[CCDirector sharedDirector]convertToGL:touchpoint];
CGFloat y=[[CCDirector sharedDirector]winSize].height/2.0f;
bulletsprite.position=ccp(20,y);
[self addChild: bulletsprite];
CCMoveTo * move=[[CCMoveTo alloc]initWithDuration:1 position:glpoint];
int
i=480/glpoint.x;
CGPoint point=ccp(490, glpoint.y*i);
CCMoveTo *move2=[[CCMoveTo alloc]initWithDuration:1 position:point];
CCCallFuncN *finish=[[CCCallFuncN alloc]initWithTarget:self selector:@selector(finish:)];
把子彈添加到數組;用於判斷是否打中目標;
[bulletarray addObject:bulletsprite];
CCSequence *sequence=[CCSequence actions:move,move2,finish, nil];
[bulletsprite runAction:sequence];
[bulletsprite release];
[move release];
}
判斷是否大中目標的函數;用循環數組比較比較範圍來獲取;
-(
void
)gamelogic
{
for
(CCSprite* bullet in bulletarray) {
CGSize buletsize=[bullet contentSize];
for
(CCSprite *taget in tagetarray) {
CGSize tagetsize=[taget contentSize];
float
x1=buletsize.width;
float
x2=tagetsize.width;
float
max=x1*0.4f+x2*0.4f;
CGFloat lon =ccpDistance(bullet.position,taget.position );
經過比較接觸範圍來判斷是否打中;
if
(lon<=max) {
[taget stopAllActions];
[bullet stopAllActions];
調用釋放函數;
[self finish:taget];
[self finish:bullet];
return
;
}
}
}
}
-(
void
)addTarget
從屏幕上釋放精靈;
-(
void
)finish:(CCNode *)node
{ 因爲數組中添加了對象,釋放時也要從數組中去除;
if
(node.tag==10) {
[bulletarray removeObject:node];
}
else
[tagetarray removeObject:node];
[node removeFromParentAndCleanup:YES];
}
作遊戲地圖
要學習 : tieldmap:地圖編譯器
opengl
Box2D 物理引擎
網絡:http gel post1
http post2
weibo分享 騰訊微博,uauth2 協議
domain 協議:1.http://
2.ftp://
3.
baidu.com是真正的域名; www.baidu.com是一臺機器是二級域名
參數間用&隔開,參數名=參數值
http:
網絡訪問模式
客戶端 發出請求 apache2 調用 訪問程序
要點:
網絡請求處理 nignx(大量鏈接時), httplight(聯接少的時候),apache2
服務器默認路徑是/library/web server/document / document 是放網頁的文件夾
讀取這個目錄下的iOS1時寫法:http:
XXXX.CGi 是服務器程序 cgi-executables 是放可執行程序的文件 在服務器訪問中映射是cgi-bin 訪問時寫成http://localhost/cgi-bin/iOS
post1真實名字是:application/x-www-form-urlencoded
功能強大順序;
post2>post1>get
他們都是上行協議;都是客戶端傳給服務器端的, 而服務器傳給客戶端的沒有區分也叫響應;
什麼時get協議:
在網址上寫的直接回車能出來的是get協議 get 時傳入到網上的東西.又能夠定義爲只有請求頭沒有請求體的請求,
入網址是http:
發到網上的時 只有請求頭:
get : /cgi-bin?srlaction=232\r\n
請求路徑和內容
host:api.douban.com\r\n
請求機器
\r\n :請求頭的結束標誌;
post1 發送格式:
請求頭:
post /cgi-bin/get.cgi\r\n
請求路徑
host:localhost\r\n
請求的機器
content-type:application/x-www-form-unlencoded\r\n
請求協議:post1
content-length :78\r\n
請求體長度
r\n
請求體:
srclatitude=40.02999&srclongitude=116.3466
get 缺陷:1.網址不可太長<1024
2.不能帶密碼;
3.不能傳文件
post1特色:1.網址小於4g
2.可一帶密碼;
read(0,input ,lengthjl) :0 指從apache2中讀數據
套接字:socket
tcp:用在穩定的鏈接:可靠的,速度快
用於:圖片,錄音,文字
udp不可靠的網絡鏈接;很是快,
用於:視頻,文件,文字
tcp:網絡傳輸;
傳輸思想:
1.服務器端:
1.生成服務器並並設置監聽接口
2.在代理的確實接收到套接字函數中 要調用等待讀取函數;這裏的等待不是新創建的套接字等待而是讓服務器底層新開一個線程等待傳人數據;
3.在代理的確實接收到數據函數中取得接收到的數據,同時要在創建等待接收數據,等待下一次傳輸;這時的tag還用先前的;由於tcp網絡傳輸一次創建聯繫,後面就無須在創建聯繫;因此省去再和服務器創建聯繫這個環節;
2.客戶端:
1.生成客戶端套接字 ;
2. 鏈接服務器,並設置網絡接入入口
3.調用代理的以服務器創建鏈接成功函數。在這裏吧鏈接開關設置爲已連鏈接
4.將數據發送到服務器
- (
void
) createServer {
allClientSockets = [[NSMutableArray alloc] init];
serverSocket = [[AsyncSocket alloc] initWithDelegate:self];
[serverSocket acceptOnPort:0x1234 error:nil];
}
- (
void
) onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
NSLog(@
"new connection is coming new %@"
,newSocket);
[allClientSockets addObject:newSocket];
int
index = [allClientSockets indexOfObject:newSocket];
[newSocket readDataWithTimeout:-1 tag:index+100];
}
- (
void
) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(
long
)tag {
int
index = [allClientSockets indexOfObject:sock];
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
recvMsgView.text = [NSString stringWithFormat:@
"%@\n%@"
, recvMsgView.text, s];
[s release];
[sock readDataWithTimeout:-1 tag:tag];
}
#pragma mark -
#pragma mark Client Part
- (
void
) createClient {
clientSocket = [[AsyncSocket alloc] initWithDelegate:self];
isConnected = NO;
}
- (
void
) connectToHost:(NSString *)ip {
static
int
index;
if
(index++)
return
;
[clientSocket connectToHost:ip onPort:0x1234 withTimeout:10 error:nil];
}
- (
void
) onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@
"已經鏈接上了 %@:%d"
, host, port);
isConnected = YES;
}
- (
void
) sendMessage:(id)arg {
NSString *ip = ipField.text;
NSString *msg = msgField.text;
NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding];
[self connectToHost:ip];
if
(isConnected == YES) {
[clientSocket writeData:msgData withTimeout:10 tag:111];
}
else
{
}
}
- (
void
) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(
long
)tag {
if
(tag == 111) {
}
}
udp 網絡傳輸
基本思想:
1。接收端端:
1.建立接收端套接字;
2.綁定網絡端口
3.等待接收數據;
4.調用代理接收到數據的函數;取出數據,並開始調用等待函數等待下次數據傳輸;
2. 發送端
1.建立發送端套接字
2.獲得接收端的ip和接收數據的網絡端口;將數據發送到該地址;
3.經過是否發送成功函數經過判斷返回的tag值來判斷是否發送成功;
- (
void
)viewDidLoad
{
[super viewDidLoad];
ipField = [[UITextField alloc] initWithFrame:CGRectMake(50, 10, 200, 30)];
ipField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:ipField];
msgField = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 150, 30)];
msgField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:msgField];
UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(220, 50, 80, 30);
[b setTitle:@
"發送"
forState:UIControlStateNormal];
[b addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
recvMsgView = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, 300, 250)];
recvMsgView.backgroundColor = [UIColor groupTableViewBackgroundColor];
[recvMsgView setEditable:NO];
[self.view addSubview:recvMsgView];
recvMsgSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[recvMsgSocket bindToPort:0x1234 error:nil];
[recvMsgSocket receiveWithTimeout:-1 tag:200];
recv2 = [[AsyncUdpSocket alloc] initWithDelegate:self];
[recv2 bindToPort:0x1235 error:nil];
senderUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
}
- (
BOOL
) onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(
long
)tag fromHost:(NSString *)host port:(UInt16)port {
if
(tag == 200) {
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *s2 = [NSString stringWithFormat:@
"%@:%d %@"
, host, port, s];
[s release];
recvMsgView.text = [NSString stringWithFormat:@
"%@\n%@"
, recvMsgView.text, s2];
[recvMsgSocket receiveWithTimeout:-1 tag:200];
}
return
YES;
}
- (
void
) sendMessage:(id)arg {
NSString *ip = ipField.text;
NSString *msg = msgField.text;
NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding];
short
port = 0x1234;
[senderUdpSocket sendData:msgData toHost:ip port:port withTimeout:10 tag:100];
NSLog(@
"aa"
);
}
- (
void
) onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(
long
)tag {
if
(tag == 100) {
NSLog(@
"數據包100已經發送成功"
);
}
}
廣播:又叫消息,觀察者,通知
ARC:內存自動管理 不需要release;
2。不用[super dealloc]
3.不能用aotorelease;
單例:一個對象,一個全局對象;
1.寫一個單例
2.單例何時釋放;不用釋放,由於時全局變量
3。如何避免實例化 :將init alloc 函數返回空;
單例命名規則:currentxxxxx, sharedxxxx, aplication xxx
arrayWithContentOfFile: 數組解析文件的方法
UITabBarItem *barItem1=[[UITabBarItem alloc]initWithTitle:@
"首頁"
image:[UIImage imageNamed:@
"關於.png"
] tag:0];
self.vc01.tabBarItem=barItem1;
self.vc01.tabBarItem.badgeValue=@
"3"
;
self.vc02.tabBarItem.badgeValue=nil;
[barItem1 release];
UITabBarItem *barItem2=[[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1];
self.vc02.tabBarItem=barItem2;
[barItem2 release];
UITabBarItem *barItem3=[[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFeatured tag:3];
self.vc03.tabBarItem=barItem3;
[barItem3 release];
NSArray *arrayVC=[NSArray arrayWithObjects:self.vc01,self.vc02,self.vc03, nil];
UITabBarController *tabBar=[[UITabBarController alloc]init];
tabBar.viewControllers=arrayVC;
self.window.rootViewController=tabBar;
[arrayVC release];
只要是添加的視圖控制器 或是什麼管理器的 話 都是加載 根視圖控制器rootViewController上面
加上UIlable UIButton view等等都是直接添加到window或是view上面的 addSubview方法
[sv addSubview:imageView];
for
(
int
i=0; i<9; i++) {
NSString *strName=[NSString stringWithFormat:@
"17_%d.jpg"
,i+1];
UIImage *image=[UIImage imageNamed:strName];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.frame=CGRectMake(20+ 97*(i%3), 20+130*(i/3), 85,120);
[self.view addSubview:imageView];
[imageView release];
}
NSString *sirName=[NSString stringWithFormat:@
"%d.png"
,i+1];
UIImage *image=[UIImage imageNamed:sirName];
[imageArray addObject:image ];
int
random=arc4random()%[imageArray count];
隨機數通常都是須要取模的 至關因而肯定生成隨機數的範圍 不至於太大的數
取模規律 8 取模生成的是0,1,2,3,4,5,6,7;
往按鈕上面添加圖片很重要的方法 使得每個圖片都是能夠點的 實際實際上點的都是button
[btn setImage:image forState:UIControlStateNormal];
btn.frame=CGRectMake(40*i , 40*j, 40, 40);
objectAtIndex 只適用於集合(數組)。可根據索引獲取對象。如:
NSArray *array=[NSArray arrayWithObjects:@
"zhangsan"
,@
"lisi"
,@
"wangwu"
,nil];
NSLog(
"%@"
,[array objectAtIndex:0]);
這時輸出的值是
'zhangsan'
.能夠看出objectAtIndex 消息是從下標0開始。
objectAtIndex從0開始 即第一個元素的位置是0
objectAtIndex 通常在數組操做中用到。可是這個數組必須是你能控制的,就是說你必須清楚地知道第幾個元素是什麼內容。
若是你不清楚你須要的元素在什麼位置,請用tag標註。
-(
void
)pressButton:(UIButton *)btn
{
static
UIButton * lastBtn=nil;
if
(lastBtn==nil) {
lastBtn=btn;
lastBtn.enabled=NO;
}
else
{
if
(lastBtn.tag==btn.tag) {
lastBtn.hidden=YES;
btn.hidden=YES;
lastBtn=nil;
}
else
{
lastBtn.enabled=YES;
lastBtn=nil;
}
}
}
UIScrollView *sv=[[UIScrollView alloc]initWithFrame:CGRectMake(30, 30, 260, 400)];
sv.backgroundColor=[UIColor redColor];
for
(
int
i=0; i<3; i++) {
UIImageView *imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@
"17_%d.jpg"
,i+1]]];
imageView.frame=CGRectMake(0+i*260, 0, 260,400);
[sv addSubview:imageView];
[imageView release];
}
sv.contentSize=CGSizeMake(260*3, 400);
sv.pagingEnabled=YES;
sv.bounces=YES;
sv.contentOffset=CGPointMake(260, 0);
[self.view addSubview:sv ];
UIScrollView *sv=[[UIScrollView alloc]initWithFrame:CGRectMake(30, 30, 260, 400)];
sv.backgroundColor=[UIColor redColor];
for
(
int
i=0; i<3; i++) {
UIImageView *imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@
"17_%d.jpg"
,i+1]]];
imageView.frame=CGRectMake(0, 0+i*400, 260,400);
[sv addSubview:imageView];
[imageView release];
}
sv.contentSize=CGSizeMake(0, 400*3);
sv.pagingEnabled=YES;
sv.bounces=YES;
sv.contentOffset=CGPointMake(0, 400);
[self.view addSubview:sv ];
- (
void
)dealloc
{
self.vc01=nil;
self.vc02=nil;
self.vc03=nil;
self.vc04=nil;
self.vc05=nil;
self.vc06=nil;
[_window release];
[super dealloc];
}
self.navigationItem.leftBarButtonItem=barBtnLef;
self.navigationItem.rightBarButtonItem=barBrnRight;
UIButton *btnLeft=[UIButton buttonWithType:UIButtonTypeCustom];
btnLeft.frame = CGRectMake(0, 0, 33, 30);
[btnLeft addTarget:self action:@selector(pressLeftNav) forControlEvents:UIControlEventTouchUpInside];
UIImage *imageLeft=[UIImage imageNamed:@
"main_left_nav"
];
[btnLeft setImage:imageLeft forState:UIControlStateNormal];
UIBarButtonItem *barBtnLef=[[UIBarButtonItem alloc]
initWithCustomView:btnLeft];
self.navigationItem.leftBarButtonItem=barBtnLef;
UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
btnRight.frame = CGRectMake(0, 0, 48, 29);
[btnRight addTarget:self action:@selector(pressRightNav) forControlEvents:UIControlEventTouchUpInside];
UIImage *imageRight = [UIImage imageNamed:@
"main_right_nav"
];
[btnRight setImage:imageRight forState:UIControlStateNormal];
UIBarButtonItem *barBrnRight=[[UIBarButtonItem alloc]initWithCustomView:btnRight];
self.navigationItem.rightBarButtonItem=barBrnRight;
navigationItem指的是導航的各類屬性 能夠引用導航按鈕 標題視圖 等等
UIImageView *ivLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@
"logo_title"
]];
ivLogo.frame = CGRectMake(0, 0, 60, 35);
self.navigationItem.titleView = ivLogo;
[ivLogo release];
UIView *bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
UIImageView *bgImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[bgView addSubview:bgImageView];
imageview.UserInteractionEnabled=YES;
NSArray *arrayTopButtonTitle = [NSArray arrayWithObjects:@
"照片"
, @
"狀態"
, @
"報到"
, nil];
NSArray *arrayTopBtnImages = [NSArray arrayWithObjects:@
"rr_pub_takephoto"
, @
"rr_pub_status"
, @
"rr_pub_checkin"
, nil];
for
(
int
i=0; i<arrayTopButtonTitle.count; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(5+105*i, 2, 100, 30);
[btn setTitle:[arrayTopButtonTitle objectAtIndex:i] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[arrayTopBtnImages objectAtIndex:i]] forState:UIControlStateNormal];
[topButtonImageView addSubview:btn];
}
常常想作的效果,主界面設置一個好看的圖片 讓後再添加button 等其餘一些東西
UIView *bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
UIImageView *bgImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@
"rr_main_background"
]];
bgImageView.frame=CGRectMake(0, 0, 320, 460);
[bgView addSubview:bgImageView];
topButtonImageView.userInteractionEnabled=YES;
[bgImageView addSubview:topButtonImageView];
bgImageView.userInteractionEnabled=YES;
注意的是:最外層view 設置的button不用設置與用戶交互 就是能夠點擊的 而當視圖上面還有小視圖的時候 並且小視圖上面還有button的時候,這個時候必須設置與用戶交互YES
topButtonImageView.userInteractionEnabled=YES;
不然雖然有button 可是點不動 呵呵;
-(
void
)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.prompt=@
"移動滑塊後將改變畫面顏色"
;
slider =[[UISlider alloc]init];
slider.frame=self.navigationController.navigationBar.bounds;
slider.minimumValue=0.0;
slider.maximumValue=1.0;
slider.value=0.0;
[slider addTarget:self action:@selector(sliderDidChange) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView=slider;
label =[[UILabel alloc]init];
label.frame=CGRectInset(self.view.bounds, 10, 10);
label.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
label.backgroundColor=[UIColor blackColor];
[self.view addSubview:label];
}
-(
void
)viewWillAppear:(
BOOL
)animated
{
[self.navigationController setNavigationBarHidden:NO animated:YES];
[self.navigationController setToolbarHidden:YES animated:YES];
[self.navigationItem setHidesBackButton:YES animated:NO];
}
-(
void
)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.navigationItem setHidesBackButton:NO animated:YES];
}
-(
void
)sliderDidChange
{
UIColor *color =[[UIColor alloc]initWithRed:(1-slider.value) green:slider.value blue:(1-slider.value)+0.4 alpha:1.0];
label.backgroundColor=color;
}
-(
void
)changColor
{
static
bool
isChange=
true
;
if
(isChange) {
self.view.backgroundColor=[UIColor redColor];
}
else
{
self.view.backgroundColor=[UIColor blackColor];
}
isChange=!isChange;
}
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeBackColor) name:@
"CHANGE_COLOR"
object:nil];
兩個控制器都必須有一樣的通知 都是同一個方法的實現纔是能夠的 顏色是能夠不同的
_tableView.tableFooterView = titleView;
上百個視圖的畫 大項目 用Single View Application來作作設計 很號的理清本身的思路 視圖太多了 很差弄 剛開始儘可能不要和代碼鏈接在一塊兒! 拖空間
工做的前兩年 仍是手寫代碼
NSString *str = [NSString stringWithFormat:@
"%02d:%02d"
,random1,random2];
- (
BOOL
)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
_searchBg = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];
[_searchBg addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_searchBg];
[_searchBg release];
return
YES;
}
- (
void
)backgroundTap:(id)sender {
UISearchBar *bar = (UISearchBar *)[self.view viewWithTag:110];
[bar resignFirstResponder];
if
(_searchBg) {
[_searchBg removeFromSuperview];
}
}
mTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
在應用UIBUtton的時候咱們有時須要同時設置圖片和文字,下面代碼僅供參考:
UIButton *_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_backButton setFrame:CGRectMake(12, 8, 64, 28)];
[_backButton setTitle:@
"返回"
forState:UIControlStateNormal];
_backButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
[_backButton setBackgroundImage:[UIImage imageNamed:@
"backButton.png"
] forState:UIControlStateNormal];
[self.view addSubview:_backButton];
出了上面的操做意外,咱們還能夠同時設置button在選中(按下以後)以及正常狀態下(沒有選中)顯示文字和圖片的不一樣,
UIButton *_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_backButton setFrame:CGRectMake(12, 8, 64, 28)];
[_backButton setTitle:@
"返回"
forState:UIControlStateNormal];
[_backButton setTitle:@
"Down"
forState:UIControlStateHighlighted];
[_backButton setBackgroundColor:[UIColor clearColor]];
[_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_backButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
[_backButton setBackgroundImage:[UIImage imageNamed:@
"backButton.png"
] forState:UIControlStateNormal];
[_backButton setBackgroundImage:[UIImage imageNamed:@
"DownButton.png"
] forState:UIControlStateNormal];
[_toolBar addSubview:_backButton];
UIBarButtonItem *btn=[[UIBarButtonItem alloc]initWithTitle:@
"返回"
style:UIBarButtonItemStyleBordered target:self action:@selector(btns:)];
self.navigationItem.leftBarButtonItem=btn;
無論有多少行 都是能夠用來代替的。。。。
-(
void
)nextPage:(id)sender
{
thirdViewController *third = [[thirdViewController alloc]init];
[self.navigationController pushViewController:third animated:YES];
[third release];
}
同步聲明一次 就應該析構一次
@property (strong, nonatomic) UISplitViewController *splitViewController;
@synthesize splitViewController = _splitViewController;
這是必須的 由於聲明一次 就會出現一個strong 計數器加上1 就須要釋放一次
- (
void
)dealloc
{
[_splitViewController release];
[super dealloc];
}
@property (nonatomic, copy) NSString *descrition;
@synthesize descrition = _descrition;
- (
void
)dealloc
{
self.descrition = nil;
[super dealloc];
}
另外須要注意的是
@property (assign, nonatomic) NSInteger i;
並且整形的變量是不須要分配內存空間的 沒有指針 因此不能給強引用 ,此時不能用到strong的
@implementation Vc02
{
NSDictionary *_dict;
}
- (
void
)dealloc
{
[_dict release];
_dict = nil;
[super dealloc];
}
sv03.contentSize=CGSizeMake(0, 1000);
sv03.pagingEnabled=YES;
sv03.bounces=YES;
sv03.contentOffset=CGPointMake(0, 320);
[self.view addSubview:sv03 ];
[sv03 release];
UIImageView *imageView01=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@
"衣裝"
]];
imageView01.frame=CGRectMake(170, 0, 150, 75);
imageView01.userInteractionEnabled =YES;
UIButton *button01=[UIButton buttonWithType:UIButtonTypeCustom];
button01.frame=CGRectMake(0, 0, 150, 75);
[button01 addTarget:self action:@selector(press01) forControlEvents:UIControlEventTouchUpInside];
[button01 setBackgroundColor:[UIColor clearColor]];
[imageView01 addSubview:button01];
[self.view addSubview:imageView01];
[imageView01 release];
UIAlertView 是不用添加到試圖上面 的
可是UIActionSheet 是必需要添加到試圖上面
全局的成員變量 須要用dealloc函數來釋放的 記住;
@property(strong,nonatomic)UILabel *lab01;
@synthesize lab01;
self.lab01=[[[UILable alloc]init]autorelease];
通常不建議這樣用 ,最好仍是用[lab01 release];
UIImageView *imageview = (UIImageView *)[self.view viewWithTag:33333];
actionsheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@
"取消"
destructiveButtonTitle:@
"分享到新浪微博"
otherButtonTitles:@
"分享到騰訊微博"
, nil];
actionsheet.delegate=self;
[actionsheet showInView:imageview];
[actionsheet release];
-(
void
)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGPoint pt=[touch locationInView:scroll02];
if
(touch.tapCount==1) {
for
(
int
i=0; i<18; i++) {
UIImageView *image=(UIImageView *)[scroll02 viewWithTag:i+1];
image.userInteractionEnabled=YES;
scroll02.userInteractionEnabled=YES;
if
(CGRectContainsPoint(image.frame, pt)) {
imageName=[NSString stringWithFormat:@
"17_%d.jpg"
,image.tag];
UIImage *image=[UIImage imageNamed:imageName];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.frame=CGRectMake(0, 0, 320, 190);
[self.view addSubview:imageView];
[imageView release];
}
}
}
}
UITouch
處理用戶響應事件,須要重載那三個觸摸的方法,開始,觸摸到,末尾,
GDataXMLDocument *doc=[[GDataXMLDocument alloc]initWithData:downloadData
options:0 error:nil];
if
(doc) {
NSArray *usersArray=[doc nodesForXPath:@
"//user"
error:nil];
for
(GDataXMLDocument *element in usersArray) {
UserItem *item=[[[UserItem alloc]init] autorelease];
item.uid=[self elementString:element name:@
"uid"
];
item.username=[self elementString:element name:@
"username"
];
item.realname=[self elementString:element name:@
"realname"
];
item.headimage=[NSString stringWithFormat:@
"http://192.168.88.8/sns%@"
,[self elementString:element name:@
"headimage"
]] ;
[dataArray addObject:item];
}
isLoading=NO;
[self.tableView reloadData];
}
高亮狀況下的button的實現方式(至關於設置兩張圖片,一張是爲默認準備的,一張是高亮準備的)
UIButton * rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
[rightbtn setImage:[UIImage imageNamed:@
"NextMenuButton.png"
] forState:UIControlStateNormal];
[rightbtn setImage:[UIImage imageNamed:@
"NextMenuButtonSelected.png"
] forState:UIControlStateHighlighted];
rightbtn.frame = CGRectMake(200, 0, 40, 40);
[rightbtn addTarget:self action:@selector(pressrightbtn) forControlEvents:UIControlEventTouchUpInside];
[navbar addSubview:leftbtn];
[navbar addSubview:rightbtn];
自定義導航欄以及導航欄上面的 按鈕 的基本方法
UINavigationBar * navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
[navbar setBackgroundImage:[UIImage imageNamed:@
"NavigatorBarBg"
] forBarMetrics:UIBarMetricsDefault];
UINavigationItem * item =[[UINavigationItem alloc] init];
UIBarButtonItem * btn1 = [[UIBarButtonItem alloc] initWithTitle:@
"返回"
style:UIBarButtonItemStyleDone target:self action:@selector(pressbtn1)];
btn1.tintColor = [UIColor yellowColor];
item.leftBarButtonItem = btn1;
[btn1 release];
[navbar pushNavigationItem:item animated:YES];
[item release];
[self.view addSubview:navbar];
[navbar release];
- (
BOOL
)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return
(interfaceOrientation == UIInterfaceOrientationPortrait);
}