# 創建第一款iPhone應用程序
現在讓我們來創建一個在iOS模擬器上運行的簡單視圖應用(空白的應用程序)。
操作步驟如下:
1、打開Xcode并選擇創建一個新的Xcode項目。

2\. 然后選擇單一視圖應用程序

3\. 接下來輸入產品名稱即應用程序名稱、組織名稱和公司標識符。

4\. 確定已經選擇自動應用計數,以自動釋放超出范圍的資源。單擊下一步。
5.選擇項目目錄并選擇創建

6\. 你將看到如下所示的頁面

屏幕上方能夠設置方向、生成和釋放。有一個部署目標,設備支持4.3及以上版本的部署目標,這些不是必須的,現在只要專注于運行該應用程序。
7\. 在下拉菜單中選擇iPhone Simulator并運行。

8\. 成功運行第一個應用程序,將得到的輸出,如下所示。

更改背景顏色使之有開始的界面生成器。選擇ViewController.xib。在右側選擇背景選項,更改顏色并運行。

在上述項目中,默認情況下,部署目標已設置為iOS6.0且自動布局將被啟用。
為確保應用程序能iOS4.3設備上正常運行,我們已經在開始創建應用程序時修改了部署目標,但我們不禁用自動布局,要取消自動布局,我們需要取消選擇自動班上復選框在文件查看器的每個nib,也就是xib文件。
Xcode項目IDE的各部分顯示如下(蘋果Xcode4用戶文檔)

在上面所示的檢查器選擇器欄中可以找到文件檢查器,且可以取消選擇自動布局。當你想要的目標只有iOS6.0的設備時,可以使用自動布局。
當然,也可以使用新功能,如當加注到iOS6時,就可以使用passbook這一功能。現在,以Ios4.3作為部署目標。
## 深入了解第一款IOS應用程序代碼
5個不同文件生成應用程序,如下所示
* AppDelegate.h
* AppDelegate.m
* ViewController.h
* ViewController.m
* ViewController.xib
我們使用單行注釋(//)來解釋簡單代碼,重要的項目代碼解釋在代碼下方。
#### AppDelegate.h
```
// Header File that provides all UI related items.
#import <UIKit/UIKit.h>
// Forward declaration (Used when class will be defined /imported in future)
@class ViewController;
// Interface for Appdelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate>
// Property window
@property (strong, nonatomic) UIWindow *window;
// Property Viewcontroller
@property (strong, nonatomic) ViewController *viewController;
//this marks end of interface
@end
```
###### 代碼說明
* AppDelegate調用UIResponder來處理Ios事件。
* 完成UIApplication的命令,提供關鍵應用程序事件,如啟動完畢,終止,等等
* 在iOS設備的屏幕上用UIWindow對象來管理和協調各種視角,它就像其它加載視圖的基本視圖一樣。通常一個應用程序只有一個窗口。
* UIViewController來處理屏幕流
#### AppDelegate.m
```
// Imports the class Appdelegate's interface
import "AppDelegate.h"
// Imports the viewcontroller to be loaded
#import "ViewController.h"
// Class definition starts here
@implementation AppDelegate
// Following method intimates us the application launched successfully
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc]
initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/* Sent when the application is about to move from active to inactive state.
This can occur for certain types of temporary interruptions
(such as an incoming phone call or SMS message)
or when the user quits the application and it begins the transition to the
background state. Use this method to pause ongoing tasks, disable timers,
and throttle down OpenGL ES frame rates. Games should use this method
to pause the game.*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/* Use this method to release shared resources, save user data, invalidate
timers, and store enough application state information to restore your
application to its current state in case it is terminated later. If your
application supports background execution, this method is called instead
of applicationWillTerminate: when the user quits.*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/* Called as part of the transition from the background to the inactive state;
here you can undo many of the changes made on entering the background.*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/* Restart any tasks that were paused (or not yet started) while the
application was inactive. If the application was previously in the background,
optionally refresh the user interface.*/
}
- (void)applicationWillTerminate:(UIApplication *)application
{
/* Called when the application is about to terminate. Save data if appropriate.
See also applicationDidEnterBackground:. */
}
@end
```
###### 代碼說明
* 此處定義UIApplication。上面定義的所有方法都是應用程序UI調動和不包含任何用戶定義的方法。
* UIWindow對象被分配用來保存應用程序分配對象。
* UIController作為窗口初始視圖控制器
* 調用makeKeyAndVisible能使窗口可見
#### ViewController.h
```
#import
// Interface for class ViewController
@interface ViewController : UIViewController
@end
```
###### 代碼說明
* ViewController類繼承UIViewController,為iOS應用程序提供基本視圖管理模型。
#### ViewController.m
```
#import "ViewController.h"
// Category, an extension of ViewController class
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
```
###### 代碼說明
* 在這里兩種方法實現UIViewController類的基類中定義
* 初始視圖加載后調用viewDidLoad中的安裝程序
* 在內存警告的情況下調用didReceviveMemoryWarning
## 簡介
在iOS中,操作(action)和輸出口(Outlet)指的是ibActions和ibOutlets,也就是ib接口生成器所在的地方。這些都和UI元素相關,我們將直觀的了解他們后探討如何實現他們。
## 步驟
1、讓我們使用第一款iPhone應用程序。
2、從導航部分中的文件中選擇ViewController.xib文件
3、從右手邊得窗口下面顯示的窗口格庫中選擇UI元素

4、拖拽UI元素到界面生成器的可視框中
5、添加標簽和紅色圓形按鈕到可視圖中

6、在工作區工具欄的右上角找到編輯器選擇按鈕,如下圖所示

**選擇編輯器按鈕**

7、編輯器區域中心有兩個窗口,ViewController.xib文件和ViewController.h
8、右擊標簽上的選擇按鈕,按住并拖動新引用參照,如下所示

9、現在放在ViewController.h之間的大括號中。也可以放在文件中,如果是這樣,必須在做這個之前已經添加了。如下所示

10\. 輸入輸出口(Outlet)的標簽名稱,這里給出的是myTitleLable。單擊鏈接,完成ibOutlet
11、同樣的,添加操作,只需右擊倒圓角矩形,選擇觸摸內心拖動它下方的大括號

12、重新命名為setTitleLable

13、 選擇ViewController.m文件,有一種方法,如下所示
```
-(IBAction) setTitleLabel:(id)sender{
}
```
14、在上述的方法內,如下所示,添加一個語句
```
[myTitleLabel setTitleText:@"Hello"];
```
15、選擇運行按鈕運行該程序,得到如下的輸出

16、單擊按鈕

17.、創建的參照(outlets)按鈕標簽已更改為對按鈕執行的操作(actions)
18、由上可知,IBOutlet將創建對UIElement的引用(此處為UILable),同樣的IBAction和UIButton通過執行操作和UIButton相鏈接。
19、當創建動作時通過選擇不同的事件你可以做不同的操作。
## 委托(Delegates)示例
假設對象A調用B來執行一項操作,操作一旦完成,對象A就必須知道對象B已完成任務且對象A將執行其他必要操作。
在上面的示例中的關鍵概念有
* A是B的委托對象
* B引用一個A
* A將實現B的委托方法
* B通過委托方法通知
創建一個委托(Delegates)對象
1\. 創建一個單一視圖的應用程序
2\. 然后選擇文件 File -> New -> File...

3\. 然后選擇Objective C單擊下一步
4\. 將SampleProtocol的子類命名為NSObject,如下所示

5\. 然后選擇創建
6.向SampleProtocol.h文件夾中添加一種協議,然后更新代碼,如下所示:
```
#import <Foundation/Foundation.h>
// Protocol definition starts here
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end
// Protocol Definition ends here
@interface SampleProtocol : NSObject
{
// Delegate to respond back
id <SampleProtocolDelegate> _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startSampleProcess; // Instance method
@end
```
7\. Implement the instance method by updating the SampleProtocol.m file as shown below.
```
#import "SampleProtocol.h"
@implementation SampleProtocol
-(void)startSampleProcess{
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate
selector:@selector(processCompleted) userInfo:nil repeats:NO];
}
@end
```
8\. 將標簽從對象庫拖到UIView,從而在ViewController.xib中添加UILabel,如下所示:

9\. 創建一個IBOutlet標簽并命名為myLabel,然后按如下所示更新代碼并在ViewController.h里顯示SampleProtocolDelegate
```
#import <UIKit/UIKit.h>
#import "SampleProtocol.h"
@interface ViewController : UIViewController<SampleProtocolDelegate>
{
IBOutlet UILabel *myLabel;
}
@end
```
10\. 完成授權方法,為SampleProtocol創建對象和調用startSampleProcess方法。如下所示,更新ViewController.m文件
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];
sampleProtocol.delegate = self;
[myLabel setText:@"Processing..."];
[sampleProtocol startSampleProcess];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Sample protocol delegate
-(void)processCompleted{
[myLabel setText:@"Process Completed"];
}
@end
```
11\. 將看到如下所示的輸出結果,最初的標簽也會繼續運行,一旦授權方法被SampleProtocol對象所調用,標簽運行程序的代碼也會更新。

## 什么是UI元素?
UI元素是我們應用程序里可以看見的任何可視元素,其中一些元素響應用戶的操作,如按鈕、文本字段,有其他的豐富內容,如圖像、標簽等。
## 如何添加UI元素?
可以在界面生成器的參與下,在代碼中添加UI元素。如果需要,我們可以使用他們其中之一。
## 我們關注的
通過代碼,將集中于添加UI元素到應用程序。比較簡單而直接的方法是使用界面生成器拖放UI元素。
## 方法
以下我們通過創建一款簡單的IOS應用程序,來解釋一些UI元素
#### 步驟
1、在第一款IOS程序里一樣,創建一個Viewbased應用程序
2、只更新ViewController.h和ViewController.m文件
3、然后我們將方法添加到ViewController.m文件中來創建UI元素
4、在viewDidLoad方法中調用此方法
5、重要的代碼行已經在代碼中通過在單行上方標注的方式進行了注釋
## 用戶界面元素列表
下面解釋具體的UI元素和其相關的功能
| 具體的UI元素 | 功能 |
| --- | --- |
| [Text Fields-文本字段](att-ios-ui-text-field.html) | 用戶界面元素,使用應用程序來獲取用戶輸入 |
| [輸入類型-TextFields](att-ios-ui-input-types.html) | 用戶可以通過使用UITextField來賦予鍵盤輸入屬性 |
| [Buttons-按鈕](att-ios-ui-buttons.html) | 用于處理用戶操作 |
| [Label-標簽](att-ios-ui-label.html) | 用于顯示靜態內容 |
| [Toolbar-工具欄](att-ios-ui-toolbar.html) | 操縱當前視圖所顯示的東西 |
| [Status Bar-狀態欄](att-ios-ui-status-bar.html) | 顯示設備的關鍵信息 |
| [Navigation Bar-導航欄](att-ios-ui-navigation-bar.html) | 包含一個可以推斷的視圖控制器,并彈出導航控制器的導航按鈕 |
| [Tab bar-選項卡欄](att-ios-ui-tab-bar.html) | 一般用于各個子任務、視圖或同一視圖中的模型之間的切換. |
| [Image View-圖像視圖](att-ios-ui-imageview.html) | 用于顯示一個簡單的圖像序列 |
| [Scroll View-滾動視圖](att-ios-ui-scrollview.html) | 用來顯示更多屏幕區域的內容 |
| [Table View-列表視圖](att-ios-ui-tableview.html) | 用于在多個行或部分中顯示可滾動列表的數據 |
| [IOS分割視圖(Split View)](att-ios-ui-splitview.html) | 用于在詳細信息窗格上顯示兩個窗格與主窗格的控制信息 |
| [Text View-文本視圖](att-ios-ui-textview.html) | 用于顯示滾動列表的文本信息可以被選中和編輯 |
| [View Transition?-視圖切換](att-ios-ui-view-transition.html) | 各種視圖查看之間的切換 |
| [Pickers-選擇器](att-ios-ui-picker.html) | 用來顯示從列表中選擇一個特定的數據 |
| [Switches-開關](att-ios-ui-switches.html) | 用作禁用和啟用操作 |
| [IOS滑塊(Sliders)](att-ios-ui-sliders.html) | 用來允許用戶在允許的值范圍內選對一個值 |
| [IOS警告對話框(Alerts)](att-ios-ui-alerts.html) | 用來給用戶提供重要的信息 |
| [IOS圖標(Icons)](att-ios-ui-icons.html) | 它是圖像,表示用于行動或描繪與應用程序相關的東西 |
## 文本字段的使用
文本字段是一個用戶界面元素,通過應用程序來獲取用戶輸入。
一個UITextfield如下所示:

重要的文本字段的屬性
* 在沒有任何用戶輸入時,顯示占位符
* 正常文本
* 自動更正型
* 鍵盤類型
* 返回鍵類型
* 清除按鈕模式
* 對齊方式
* 委托
## 更新xib中的屬性
可以在Utility area(實用區域,窗口的右側)更改xib在屬性查看器中的文本字段屬性。

## 文本字段委托
我們可以通過右擊?UIElement?界面生成器中設置委托并將它連接到文件的所有者,如下所示:

使用委托的步驟:
* 1.設置委托如上圖所示
* 2.添加委托到您的響應類
* 3.執行文本字段代表,重要的文本字段代表如下:
```
- (void)textFieldDidBeginEditing:(UITextField *)textField
```
```
- (void)textFieldDidEndEditing:(UITextField *)textField
```
* 4.正如其名稱所暗示,上述兩個委托分別叫做編輯的文本字段和結束編輯
* 5\. 其他的委托請查看 UITextDelegate Protocol 參考手冊。
## 實例
以下我們使用簡單的實例來創建UI元素
ViewController 類將采用UITextFieldDelegate,修改ViewController.h文件,如下所示:
將方法addTextField添加到我們的 ViewController.m 文件
然后在 viewDidLoad 方法中調用此方法
在ViewController.m中更新viewDidLoad,如下所示
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//The custom method to create our textfield is called
[self addTextField];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)addTextField{
// This allocates a label
UILabel *prefixLabel = [[UILabel alloc]initWithFrame:CGRectZero];
//This sets the label text
prefixLabel.text =@"## ";
// This sets the font for the label
[prefixLabel setFont:[UIFont boldSystemFontOfSize:14]];
// This fits the frame to size of the text
[prefixLabel sizeToFit];
// This allocates the textfield and sets its frame
UITextField *textField = [[UITextField alloc] initWithFrame:
CGRectMake(20, 50, 280, 30)];
// This sets the border style of the text field
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment =
UIControlContentVerticalAlignmentCenter;
[textField setFont:[UIFont boldSystemFontOfSize:12]];
//Placeholder text is displayed when no text is typed
textField.placeholder = @"Simple Text field";
//Prefix label is set as left view and the text starts after that
textField.leftView = prefixLabel;
//It set when the left prefixLabel to be displayed
textField.leftViewMode = UITextFieldViewModeAlways;
// Adds the textField to the view.
[self.view addSubview:textField];
// sets the delegate to the current class
textField.delegate = self;
}
// pragma mark is used for easy access of code in Xcode
#pragma mark - TextField Delegates
// This method is called once we click inside the textField
-(void)textFieldDidBeginEditing:(UITextField *)textField{
NSLog(@"Text field did begin editing");
}
// This method is called once we complete editing
-(void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(@"Text field ended editing");
}
// This method enables or disables the processing of return key
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)viewDidUnload {
label = nil;
[super viewDidUnload];
}
@end
```
運行該應用程序會看到下面的輸出

委托調用的方法基于用戶操作。要知道調用委托時請參閱控制臺輸出。
## 為什么使用不同的輸入類型?
鍵盤輸入的類型幫助我們從用戶獲取必需的輸入。
它移除不需要的鍵,并包括所需的部分。用戶可以通過使用?UITextField?的鍵盤屬性設置輸入的類型。
* 如:文本字段( textField)。 ?keyboardType = UIKeyboardTypeDefault
鍵盤輸入類型
| 輸入的類型 | 描述 |
| --- | --- |
| UIKeyboardTypeASCIICapable | 鍵盤包括所有標準的?ASCII?字符。 |
| UIKeyboardTypeNumbersAndPunctuation | 鍵盤顯示數字和標點。 |
| UIKeyboardTypeURL | 鍵盤的?URL?項優化。 |
| UIKeyboardTypeNumberPad | 鍵盤用于?PIN?輸入和顯示一個數字鍵盤。 |
| UIKeyboardTypePhonePad | 鍵盤對輸入電話號碼進行了優化。 |
| UIKeyboardTypeNamePhonePad | 鍵盤用于輸入姓名或電話號碼。 |
| UIKeyboardTypeEmailAddress | 鍵盤對輸入電子郵件地址的優化。 |
| UIKeyboardTypeDecimalPad | 鍵盤用來輸入十進制數字。 |
| UIKeyboardTypeTwitter | 鍵盤對?twitter @?和?#?符號進行了優化。 |
## 添加自定義方法?addTextFieldWithDifferentKeyboard
```
-(void) addTextFieldWithDifferentKeyboard{
UITextField *textField1= [[UITextField alloc]initWithFrame:
CGRectMake(20, 50, 280, 30)];
textField1.delegate = self;
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.placeholder = @"Default Keyboard";
[self.view addSubview:textField1];
UITextField *textField2 = [[UITextField alloc]initWithFrame:
CGRectMake(20, 100, 280, 30)];
textField2.delegate = self;
textField2.borderStyle = UITextBorderStyleRoundedRect;
textField2.keyboardType = UIKeyboardTypeASCIICapable;
textField2.placeholder = @"ASCII keyboard";
[self.view addSubview:textField2];
UITextField *textField3 = [[UITextField alloc]initWithFrame:
CGRectMake(20, 150, 280, 30)];
textField3.delegate = self;
textField3.borderStyle = UITextBorderStyleRoundedRect;
textField3.keyboardType = UIKeyboardTypePhonePad;
textField3.placeholder = @"Phone pad keyboard";
[self.view addSubview:textField3];
UITextField *textField4 = [[UITextField alloc]initWithFrame:
CGRectMake(20, 200, 280, 30)];
textField4.delegate = self;
textField4.borderStyle = UITextBorderStyleRoundedRect;
textField4.keyboardType = UIKeyboardTypeDecimalPad;
textField4.placeholder = @"Decimal pad keyboard";
[self.view addSubview:textField4];
UITextField *textField5= [[UITextField alloc]initWithFrame:
CGRectMake(20, 250, 280, 30)];
textField5.delegate = self;
textField5.borderStyle = UITextBorderStyleRoundedRect;
textField5.keyboardType = UIKeyboardTypeEmailAddress;
textField5.placeholder = @"Email keyboard";
[self.view addSubview:textField5];
UITextField *textField6= [[UITextField alloc]initWithFrame:
CGRectMake(20, 300, 280, 30)];
textField6.delegate = self;
textField6.borderStyle = UITextBorderStyleRoundedRect;
textField6.keyboardType = UIKeyboardTypeURL;
textField6.placeholder = @"URL keyboard";
[self.view addSubview:textField6];
}
```
在?ViewController.m?中更新?viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
//The custom method to create textfield with different keyboard input
[self addTextFieldWithDifferentKeyboard];
//Do any additional setup after loading the view, typically from a nib
}
```
## 輸出
現在當我們運行應用程序時我們就會得到下面的輸出:

選擇不同的文本區域我們將看到不同的鍵盤。
## 按鈕使用
按鈕用于處理用戶操作。它截取觸摸事件,并將消息發送到目標對象。
## 圓角矩形按鈕

## 在?xib?中的按鈕屬性
您可以在Utility area(實用區域,窗口的右側)的屬性檢查器的更改 ?xib 按鈕屬性。

按鈕類型
* UIButtonTypeCustom
* UIButtonTypeRoundedRect
* UIButtonTypeDetailDisclosure
* UIButtonTypeInfoLight
* UIButtonTypeInfoDark
* UIButtonTypeContactAdd
重要的屬性
* imageView
* titleLabel
重要的方法
```
+ (id)buttonWithType:(UIButtonType)buttonType
```
```
- (UIImage *)backgroundImageForState:(UIControlState)state
```
```
- (UIImage *)imageForState:(UIControlState)state
```
```
- (void)setTitle:(NSString *)title forState:(UIControlState)state
```
```
- (void)addTarget:(id)target action:(SEL)action forControlEvents: (UIControlEvents) controlEvents
```
添加自定義方法?addDifferentTypesOfButton
```
-(void)addDifferentTypesOfButton
{
// A rounded Rect button created by using class method
UIButton *roundRectButton = [UIButton buttonWithType:
UIButtonTypeRoundedRect];
[roundRectButton setFrame:CGRectMake(60, 50, 200, 40)];
// sets title for the button
[roundRectButton setTitle:@"Rounded Rect Button" forState:
UIControlStateNormal];
[self.view addSubview:roundRectButton];
UIButton *customButton = [UIButton buttonWithType: UIButtonTypeCustom];
[customButton setBackgroundColor: [UIColor lightGrayColor]];
[customButton setTitleColor:[UIColor blackColor] forState:
UIControlStateHighlighted];
//sets background image for normal state
[customButton setBackgroundImage:[UIImage imageNamed:
@"Button_Default.png"]
forState:UIControlStateNormal];
//sets background image for highlighted state
[customButton setBackgroundImage:[UIImage imageNamed:
@"Button_Highlighted.png"]
forState:UIControlStateHighlighted];
[customButton setFrame:CGRectMake(60, 100, 200, 40)];
[customButton setTitle:@"Custom Button" forState:UIControlStateNormal];
[self.view addSubview:customButton];
UIButton *detailDisclosureButton = [UIButton buttonWithType:
UIButtonTypeDetailDisclosure];
[detailDisclosureButton setFrame:CGRectMake(60, 150, 200, 40)];
[detailDisclosureButton setTitle:@"Detail disclosure" forState:
UIControlStateNormal];
[self.view addSubview:detailDisclosureButton];
UIButton *contactButton = [UIButton buttonWithType:
UIButtonTypeContactAdd];
[contactButton setFrame:CGRectMake(60, 200, 200, 40)];
[self.view addSubview:contactButton];
UIButton *infoDarkButton = [UIButton buttonWithType:
UIButtonTypeInfoDark];
[infoDarkButton setFrame:CGRectMake(60, 250, 200, 40)];
[self.view addSubview:infoDarkButton];
UIButton *infoLightButton = [UIButton buttonWithType:
UIButtonTypeInfoLight];
[infoLightButton setFrame:CGRectMake(60, 300, 200, 40)];
[self.view addSubview:infoLightButton];
}
```
## 注意:
我們將命名為"Button_Default.png"和"Button_Highlighted.png"的個圖像添加到我們的項目,可以通過將圖像拖到列出了我們的項目文件的導航區域來完成。
在?ViewController.m?中更新?viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
//The custom method to create our different types of button is called
[self addDifferentTypesOfButton];
//Do any additional setup after loading the view, typically from a nib
}
```
## 輸出
現在當我們運行應用程序時我們就會得到下面的輸出:

## 標簽的使用
標簽用于顯示靜態內容,包括單獨的一行或多行。
重要的屬性
* textAlignment
* textColor
* text
* numberOflines
* lineBreakMode
## 添加自定義方法?addLabel
```
-(void)addLabel{
UILabel *aLabel = [[UILabel alloc]initWithFrame:
CGRectMake(20, 200, 280, 80)];
aLabel.numberOfLines = 0;
aLabel.textColor = [UIColor blueColor];
aLabel.backgroundColor = [UIColor clearColor];
aLabel.textAlignment = UITextAlignmentCenter;
aLabel.text = @"This is a sample text\n of multiple lines.
here number of lines is not limited.";
[self.view addSubview:aLabel];
}
```
在?ViewController.m?中更新?viewDidLoad,如下所示:
```
- (void)viewDidLoad
{
[super viewDidLoad];
//The custom method to create our label is called
[self addLabel];
// Do any additional setup after loading the view, typically from a nib.
}
```
## 輸出
運行應用程序,就會得到下面的輸出:

## 工具欄的使用
我們可以使用工具欄修改視圖元素。
如,郵件應用程序里的收件箱欄中有刪除、分享、答復等等。如下所示:

重要的屬性
* barStyle
* items
## 添加自定義方法?addToolbar
```
-(void)addToolbar
{
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem *customItem1 = [[UIBarButtonItem alloc]
initWithTitle:@"Tool1" style:UIBarButtonItemStyleBordered
target:self action:@selector(toolBarItem1:)];
UIBarButtonItem *customItem2 = [[UIBarButtonItem alloc]
initWithTitle:@"Tool2" style:UIBarButtonItemStyleDone
target:self action:@selector(toolBarItem2:)];
NSArray *toolbarItems = [NSArray arrayWithObjects:
customItem1,spaceItem, customItem2, nil];
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:
CGRectMake(0, 366+54, 320, 50)];
[toolbar setBarStyle:UIBarStyleBlackOpaque];
[self.view addSubview:toolbar];
[toolbar setItems:toolbarItems];
}
```
為了解所執行的操作我們在我們的ViewController.xib中添加UILabel Iboutlet并為?UILabel?創建命名為標簽的IBoutlet。
我們還需要添加兩個方法來執行,如下所示的工具欄項的操作:
```
-(IBAction)toolBarItem1:(id)sender{
[label setText:@"Tool 1 Selected"];
}
-(IBAction)toolBarItem2:(id)sender{
[label setText:@"Tool 2 Selected"];
}
```
在ViewController.m中更新?viewDidLoad,如下所示:
```
- (void)viewDidLoad
{
[super viewDidLoad];
// The method hideStatusbar called after 2 seconds
[self addToolbar];
// Do any additional setup after loading the view, typically from a nib.
}
```
## 輸出
現在當我們運行該應用程序我們會看到下面的輸出。

單擊我們得到的?tool1?和?tool2?欄按鈕

## 狀態欄的使用
狀態欄顯示設備的關鍵信息。
* 設備模型或網絡提供商
* 網絡信號強度
* 電池使用量
* 時間
狀態欄如下所示:

隱藏狀態欄的方法
```
[[UIApplication sharedApplication] setStatusBarHidden:YES];
```
## 另一種隱藏狀態欄的方法
我們還可以通過添加行,并在info.plist?的幫助下選擇?UIStatusBarHidden?隱藏狀態欄,并使其值為否(NO)。
## 在類中添加自定義方法?hideStatusbar
它隱藏狀態欄進行動畫處理,并也調整我們認為占據狀態欄空間的大小。
```
-(void)hideStatusbar{
[[UIApplication sharedApplication] setStatusBarHidden:YES
withAnimation:UIStatusBarAnimationFade];
[UIView beginAnimations:@"Statusbar hide" context:nil];
[UIView setAnimationDuration:0.5];
[self.view setFrame:CGRectMake(0, 0, 320, 480)];
[UIView commitAnimations];
}
```
在?ViewController.m?中更新?viewDidLoad,如下所示:
```
- (void)viewDidLoad
{
[super viewDidLoad];
// The method hideStatusbar called after 2 seconds
[self performSelector:@selector(hideStatusbar)
withObject:nil afterDelay:2.0];
// Do any additional setup after loading the view, typically from a nib.
}
```
## 初始輸出以及2秒后輸出

## IOS導航欄的使用
導航欄包含導航控制器的導航的按鈕。在導航欄中的標題是當前視圖控制器的標題。
## 示例代碼和步驟
1.創視圖應用程序
2.?現在,選擇應用程序?Delegate.h?,添加導航控制器的屬性,如下所示:
```
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (strong, nonatomic) UINavigationController *navController;
@end
```
3\. 更新應用程序: didFinishLaunchingWithOptions:方法,在AppDelegate.m文件分配的導航控制器,并使其成為窗口的根視圖控制器,如下所示:
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc]
initWithNibName:@"ViewController" bundle:nil];
//Navigation controller init with ViewController as root
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:self.viewController];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
return YES;
}
```
4.現在,通過選擇**File**?->?**New**?->**File...**?-> Objective C Class?添加新的類文件TempViewController,然后將類命名 TempViewController?與?UIViewController?的子類。
5.在ViewController.h中添加navButon,如下所示
```
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
UIButton *navButton;
}
@end
```
6.現在添加方法addNavigationBarItem并在viewDidLoad調用方法
7\. 為導航項創建方法
8.?我們還需要創建另一種方法到另一視圖控制器?TempViewController。
9.?更新后的ViewController.m,如下所示:
```
// ViewController.m
#import "ViewController.h"
#import "TempViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self addNavigationBarButton];
//Do any additional setup after loading the view, typically from a nib
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)pushNewView:(id)sender{
TempViewController *tempVC =[[TempViewController alloc]
initWithNibName:@"TempViewController" bundle:nil];
[self.navigationController pushViewController:tempVC animated:YES];
}
-(IBAction)myButtonClicked:(id)sender{
// toggle hidden state for navButton
[navButton setHidden:!nav.hidden];
}
-(void)addNavigationBarButton{
UIBarButtonItem *myNavBtn = [[UIBarButtonItem alloc] initWithTitle:
@"MyButton" style:UIBarButtonItemStyleBordered target:
self action:@selector(myButtonClicked:)];
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
[self.navigationItem setRightBarButtonItem:myNavBtn];
// create a navigation push button that is initially hidden
navButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[navButton setFrame:CGRectMake(60, 50, 200, 40)];
[navButton setTitle:@"Push Navigation" forState:UIControlStateNormal];
[navButton addTarget:self action:@selector(pushNewView:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:navButton];
[navButton setHidden:YES];
}
@end
```
10.?現在當我們運行應用程序時我們就會得到下面的輸出

11.?單擊?MyButton?導航按鈕,切換導航按鈕可見性
12.?單擊導航按鈕,顯示另一個視圖控制器,如下所示

## IOS選項卡欄的使用
它一般用于在同一視圖中各個子任務、 視圖或的模型之間切換。
選項卡欄的示例如下所示:

重要的屬性
* backgroundImage
* items
* selectedItem
示例代碼和步驟
1\. 創建一個新的項目,選擇 ?**Tabbed Application**?替代視圖應用程序?,點擊下一步, 輸入項目名稱和選擇?**create**.
2.?這里默認創建兩個視圖控制器和標簽欄添加到我們的應用程序。
3\. **AppDelegate.m didFinishLaunchingWithOptions**方法如下:
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
// Override point for customization after application launch.
UIViewController *viewController1 = [[FirstViewController alloc]
initWithNibName:@"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[SecondViewController alloc]
initWithNibName:@"SecondViewController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[viewController1,
viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
```
4.?兩個視圖控制器被用來分配作為選項卡欄控制器的視圖控制器
5.?運行應用程序,得到如下結果:

## 圖像視圖的使用
圖像視圖用于顯示單個圖像或動畫序列的圖像。
重要的屬性
* image
* highlightedImage
* userInteractionEnabled
* animationImages
* animationRepeatCount
## 重要的方法
```
- (id)initWithImage:(UIImage *)image
```
```
- (id)initWithImage:(UIImage *)image highlightedImage:
(UIImage *)highlightedImage
```
```
- (void)startAnimating
```
```
- (void)stopAnimating
```
### 添加自定義方法 addImageView
```
-(void)addImageView{
UIImageView *imgview = [[UIImageView alloc]
initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"AppleUSA1.jpg"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
}
```
### 添加另一個自定義方法 addImageViewWithAnimation
這種方法解釋了如何對imageView 中的圖像進行動畫處理
```
-(void)addImageViewWithAnimation{
UIImageView *imgview = [[UIImageView alloc]
initWithFrame:CGRectMake(10, 10, 300, 400)];
// set an animation
imgview.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"AppleUSA1.jpg"],
[UIImage imageNamed:@"AppleUSA2.jpg"], nil];
imgview.animationDuration = 4.0;
imgview.contentMode = UIViewContentModeCenter;
[imgview startAnimating];
[self.view addSubview:imgview];
}
```
**注意:** 我們必須添加命名為"AppleUSA1.jpg"和"AppleUSA2.jpg"到我們的項目,可以通過將圖像拖到我們導航區域,其中列出了我們的項目文件所做的圖像。
在 ViewController.m 中更新 viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addImageView];
}
```
## 滾動視圖的使用
如果內容超出屏幕的大小就會使用到滾動視圖來顯示隱藏的部分。
它可以包含所有的其他用戶界面元素 如圖像視圖、 標簽、 文本視圖甚至另一個滾動視圖。
### 重要的屬性
* contentSize
* contentInset
* contentOffset
* delegate
### 重要的方法
```
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
```
```
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
```
### 重要的委托方法
在ViewController.h中,加入<uiscrollviewdelegate>滾動視圖和聲明滾動視圖讓類符合委托協議,如下所示:</uiscrollviewdelegate>
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIScrollViewDelegate>
{
UIScrollView *myScrollView;
}
@end
```
添加自定義方法 addScrollView
```
-(void)addScrollView{
myScrollView = [[UIScrollView alloc]initWithFrame:
CGRectMake(20, 20, 280, 420)];
myScrollView.accessibilityActivationPoint = CGPointMake(100, 100);
imgView = [[UIImageView alloc]initWithImage:
[UIImage imageNamed:@"AppleUSA.jpg"]];
[myScrollView addSubview:imgView];
myScrollView.minimumZoomScale = 0.5;
myScrollView.maximumZoomScale = 3;
myScrollView.contentSize = CGSizeMake(imgView.frame.size.width,
imgView.frame.size.height);
myScrollView.delegate = self;
[self.view addSubview:myScrollView];
}
```
**注意:** 我們必須添加一個命名為"AppleUSA1.jpg"到我們的項目,可以通過將圖像拖到我們導航區域,其中列出了我們的項目文件所做的圖像。圖像應高于設備的高度。
### ViewController.m中實現scrollView 委托
```
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return imgView;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
NSLog(@"Did end decelerating");
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
// NSLog(@"Did scroll");
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView
willDecelerate:(BOOL)decelerate{
NSLog(@"Did end dragging");
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
NSLog(@"Did begin decelerating");
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
NSLog(@"Did begin dragging");
}
```
### 在 ViewController.m 中更新 viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addScrollView];
//Do any additional setup after loading the view, typically from a nib
}
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出。一旦滾動滾動視圖,將能夠查看圖像的其余部分:

## 表格視圖的使用
IOS表格視圖由單元格 (一般可重復使用) 組成,用于顯示垂直滾動的視圖。
在iOS 中,表格視圖用于顯示數據列表,如聯系人、待辦事項或購物項列表。
### 重要的屬性
* delegate
* dataSource
* rowHeight
* sectionFooterHeight
* sectionHeaderHeight
* separatorColor
* tableHeaderView
* tableFooterView
### 重要的方法
```
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
```
```
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation
```
```
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
```
```
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
forIndexPath:(NSIndexPath *)indexPath
```
```
- (void)reloadData
```
```
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation
```
```
- (NSArray *)visibleCells
```
### 示例代碼和步驟
1.在ViewController.xib中添加表格視圖,如下所示

2\. 通過右鍵單擊并選擇數據源和委托將委托和數據源設定到"File's Owner(文件的所有者)"。設置數據源如下所示

3.為表格視圖創建IBOutlet的并將其命名為myTableView。如以下圖片中所示


4\. 為擁有數據,添加一個NSMutableArray使其能夠在列表格視圖中顯示
5.ViewController應采用的UITableViewDataSource和UITableViewDelegate協議。ViewController.h代碼如下所示
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDataSource,
UITableViewDelegate>
{
IBOutlet UITableView *myTableView;
NSMutableArray *myData;
}
@end
```
6.執行所需的表格視圖委托和數據源的方法。更新ViewController.m,如下所示
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// table view data is being set here
myData = [[NSMutableArray alloc]initWithObjects:
@"Data 1 in array",@"Data 2 in array",@"Data 3 in array",
@"Data 4 in array",@"Data 5 in array",@"Data 5 in array",
@"Data 6 in array",@"Data 7 in array",@"Data 8 in array",
@"Data 9 in array", nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table View Data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section{
return [myData count]/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSString *stringForCell;
if (indexPath.section == 0) {
stringForCell= [myData objectAtIndex:indexPath.row];
}
else if (indexPath.section == 1){
stringForCell= [myData objectAtIndex:indexPath.row+ [myData count]/2];
}
[cell.textLabel setText:stringForCell];
return cell;
}
// Default is 1 if not implemented
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section{
NSString *headerTitle;
if (section==0) {
headerTitle = @"Section 1 Header";
}
else{
headerTitle = @"Section 2 Header";
}
return headerTitle;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:
(NSInteger)section{
NSString *footerTitle;
if (section==0) {
footerTitle = @"Section 1 Footer";
}
else{
footerTitle = @"Section 2 Footer";
}
return footerTitle;
}
#pragma mark - TableView delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Section:%d Row:%d selected and its data is %@",
indexPath.section,indexPath.row,cell.textLabel.text);
}
@end
```
7.現在當我們運行應用程序時我們就會得到下面的輸出

## 分割視圖的使用
分割視圖是 iPad 的特定視圖控制器用于管理兩個視圖控制器,在左側是一個主控制器,其右側是一個詳細信息視圖控制器。 重要的屬性
* delegate
* viewControllers
## 示例代碼和步驟
1.創建一個新項目,選擇Master Detail Application并單擊下一步,輸入項目名稱,然后選擇創建。
2.簡單的分割視圖控制器與母版中的表視圖是默認創建的。
3.在這里我們為我們創建的下列文件。
* AppDelegate.h
* AppDelegate.m
* DetailViewController.h
* DetailViewController.m
* DetailViewController.xib
* MasterViewController.h
* MasterViewController.m
* MasterViewController.xib
4\. AppDelegate.h文件如下所示
```
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UISplitViewController *splitViewController;
@end
```
5.在AppDelegate.m中的didFinishLaunchingWithOptions方法,如下所示
```
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
bounds]];
// Override point for customization after application launch.
MasterViewController *masterViewController = [[MasterViewController
alloc] initWithNibName:@"MasterViewController" bundle:nil];
UINavigationController *masterNavigationController =
[[UINavigationController alloc] initWithRootViewController:
masterViewController];
DetailViewController *detailViewController =
[[DetailViewController alloc] initWithNibName:@"DetailViewController"
bundle:nil];
UINavigationController *detailNavigationController =
[[UINavigationController alloc] initWithRootViewController:
detailViewController];
masterViewController.detailViewController = detailViewController;
self.splitViewController = [[UISplitViewController alloc] init];
self.splitViewController.delegate = detailViewController;
self.splitViewController.viewControllers =
@[masterNavigationController, detailNavigationController];
self.window.rootViewController = self.splitViewController;
[self.window makeKeyAndVisible];
return YES;
}
```
6\. MasterViewController.h,如下所示
```
#import <UIKit/UIKit.h>
@class DetailViewController;
@interface MasterViewController : UITableViewController
@property (strong, nonatomic) DetailViewController *detailViewController;
@end
```
7\. MasterViewController.m,如下所示
```
#import "MasterViewController.h"
#import "DetailViewController.h"
@interface MasterViewController () {
NSMutableArray *_objects;
}
@end
@implementation MasterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)
nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem: UIBarButtonSystemItemAdd
target:self action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:
UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return _objects.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDate *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:
(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:
(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:
UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into
//the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:
(NSIndexPath *) fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:
(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
NSString *stringFromDate = [formatter stringFromDate:object];
self.detailViewController.detailDescriptionLabel.text = stringFromDate;
}
@end
```
8\. DetailViewController.h ,如下所示
```
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
<UISplitViewControllerDelegate>
@property (strong, nonatomic) id detailItem;
@property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
@end
```
9\. DetailViewController.m ,如下所示
```
#import "DetailViewController.h"
@interface DetailViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
@end
@implementation DetailViewController
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
if (self.masterPopoverController != nil) {
[self.masterPopoverController dismissPopoverAnimated:YES];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:
(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Detail", @"Detail");
}
return self;
}
#pragma mark - Split view
- (void)splitViewController:(UISplitViewController *)splitController
willHideViewController:(UIViewController *)viewController withBarButtonItem:
(UIBarButtonItem *)barButtonItem forPopoverController:
(UIPopoverController *)popoverController
{
barButtonItem.title = NSLocalizedString(@"Master", @"Master");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}
- (void)splitViewController:(UISplitViewController *)splitController
willShowViewController:(UIViewController *)viewController
invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
// Called when the view is shown again in the split view,
//invalidating the button and popover controller.
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}
@end
```
10.現在當我們運行應用程序時,在橫向模式下我們會得到下面的輸出

11\. 當我們切換到縱向模式,我們會獲得下面的輸出:

## IOS文本視圖的使用
文本視圖用于顯示多行滾動的文本。
### 重要屬性
* dataDetectorTypes
* delegate
* editable
* inputAccessoryView
* inputView
* text
* textAlignment
* textColor
## 重要的委托方法
```
-(void)textViewDidBeginEditing:(UITextView *)textView
```
```
-(void)textViewDidEndEditing:(UITextView *)textView
```
```
-(void)textViewDidChange:(UITextView *)textView
```
```
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
```
### 添加自定義方法 addTextView
```
-(void)addTextView{
myTextView = [[UITextView alloc]initWithFrame:
CGRectMake(10, 50, 300, 200)];
[myTextView setText:@"Lorem ipsum dolor sit er elit lamet, consectetaur
cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum. Nam liber te
conscient to factor tum poen legum odioque civiuda.
Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing
pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aiqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum. Nam liber te conscient
to factor tum poen legum odioque civiuda."];
myTextView.delegate = self;
[self.view addSubview:myTextView];
}
```
在 ViewController.m 中執行 textView 委托
```
#pragma mark - Text View delegates
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:
(NSRange)range replacementText:(NSString *)text{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
}
return YES;
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
NSLog(@"Did begin editing");
}
-(void)textViewDidChange:(UITextView *)textView{
NSLog(@"Did Change");
}
-(void)textViewDidEndEditing:(UITextView *)textView{
NSLog(@"Did End editing");
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
[textView resignFirstResponder];
return YES;
}
```
修改 ViewController.m 中的 viewDidLoad方法,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addTextView];
}
```
### 結果輸出
現在當我們運行該應用程序我們會看到下面的輸出

## IOS視圖切換的使用
視圖切換通過一系列動畫效果實現,包括折疊切換、爆炸切換、卡片式切換等等。
### 修改 ViewController.xib,如下所示

在 xib 中創建按鈕的操作
### 修改 ViewController.h
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
UIView *view1;
UIView *view2;
}
-(IBAction)flipFromLeft:(id)sender;
-(IBAction)flipFromRight:(id)sender;
-(IBAction)flipFromTop:(id)sender;
-(IBAction)flipFromBottom:(id)sender;
-(IBAction)curlUp:(id)sender;
-(IBAction)curlDown:(id)sender;
-(IBAction)dissolve:(id)sender;
-(IBAction)noTransition:(id)sender;
@end
```
在 ViewController 類中聲明兩個視圖的實例。ViewController.h文件代碼如下:
### 修改 ViewController.m
我們將添加自定義方法setUpView來初始化視圖。
我們還將創建了另一種方法doTransitionWithType: 實現view1切換到view2,反之亦然。
后我們將執行之前創建的操作的方法即調用 doTransitionWithType: 方法與切換類型。ViewController.m代碼如下:
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self setUpView];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)setUpView{
view1 = [[UIView alloc]initWithFrame:self.view.frame];
view1.backgroundColor = [UIColor lightTextColor];
view2 = [[UIView alloc]initWithFrame:self.view.frame];
view2.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view1];
[self.view sendSubviewToBack:view1];
}
-(void)doTransitionWithType:(UIViewAnimationTransition)animationTransitionType{
if ([[self.view subviews] containsObject:view2 ]) {
[UIView transitionFromView:view2
toView:view1
duration:2
options:animationTransitionType
completion:^(BOOL finished){
[view2 removeFromSuperview];
}];
[self.view addSubview:view1];
[self.view sendSubviewToBack:view1];
}
else{
[UIView transitionFromView:view1
toView:view2
duration:2
options:animationTransitionType
completion:^(BOOL finished){
[view1 removeFromSuperview];
}];
[self.view addSubview:view2];
[self.view sendSubviewToBack:view2];
}
}
-(IBAction)flipFromLeft:(id)sender
{
[self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromLeft];
}
-(IBAction)flipFromRight:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromRight];
}
-(IBAction)flipFromTop:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromTop];
}
-(IBAction)flipFromBottom:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromBottom];
}
-(IBAction)curlUp:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionCurlUp];
}
-(IBAction)curlDown:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionCurlDown];
}
-(IBAction)dissolve:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionCrossDissolve];
}
-(IBAction)noTransition:(id)sender{
[self doTransitionWithType:UIViewAnimationOptionTransitionNone];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出

您可以選擇不同的按鈕,看切換是如何工作。選擇蜷縮切換將效果如下所示

## 選擇器的使用
選擇器是一個可滾動視圖,用于選取列表項中的值。
### 重要的屬性
* delegate
* dataSource
### 重要的方法
```
- (void)reloadAllComponents
```
```
- (void)reloadComponent:(NSInteger)component
```
```
- (NSInteger)selectedRowInComponent:(NSInteger)component
```
```
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component
? animated:(BOOL)animated
```
### 修改 ViewController.h
我們將添加一個文本字段、選擇器視圖和一個數組。
我們將采用UITextFieldDelegate、UIPickerViewDataSource、UIPickerViewDelegate的協議。ViewController.h文件代碼如下所示:
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
{
UITextField *myTextField;
UIPickerView *myPickerView;
NSArray *pickerArray;
}
@end
```
### 添加自定義方法 addPickerView
```
-(void)addPickerView{
pickerArray = [[NSArray alloc]initWithObjects:@"Chess",
@"Cricket",@"Football",@"Tennis",@"Volleyball", nil];
myTextField = [[UITextField alloc]initWithFrame:
CGRectMake(10, 100, 300, 30)];
myTextField.borderStyle = UITextBorderStyleRoundedRect;
myTextField.textAlignment = UITextAlignmentCenter;
myTextField.delegate = self;
[self.view addSubview:myTextField];
[myTextField setPlaceholder:@"Pick a Sport"];
myPickerView = [[UIPickerView alloc]init];
myPickerView.dataSource = self;
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithTitle:@"Done" style:UIBarButtonItemStyleDone
target:self action:@selector(done:)];
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:
CGRectMake(0, self.view.frame.size.height-
myDatePicker.frame.size.height-50, 320, 50)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
NSArray *toolbarItems = [NSArray arrayWithObjects:
doneButton, nil];
[toolBar setItems:toolbarItems];
myTextField.inputView = myPickerView;
myTextField.inputAccessoryView = toolBar;
}
```
### 執行委托,如下所示:
```
#pragma mark - Text field delegates
-(void)textFieldDidBeginEditing:(UITextField *)textField{
if ([textField.text isEqualToString:@""]) {
[self dateChanged:nil];
}
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
return [pickerArray count];
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
[myTextField setText:[pickerArray objectAtIndex:row]];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component{
return [pickerArray objectAtIndex:row];
}
```
在ViewController.m修改viewDidLoad,如下所示:
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addPickerView];
}
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出:

文本選擇器視圖如下所示,我們可以選取我們需要的值:

## IOS開關的使用
開關用于打開和關閉狀態之間的切換。
重要的屬性
* onImage
* offImage
* on
### 重要的方法
```
- (void)setOn:(BOOL)on animated:(BOOL)animated
```
### 添加自定義方法 addSwitch 和開關
```
-(IBAction)switched:(id)sender{
NSLog(@"Switch current state %@", mySwitch.on ? @"On" : @"Off");
}
-(void)addSwitch{
mySwitch = [[UISwitch alloc] init];
[self.view addSubview:mySwitch];
mySwitch.center = CGPointMake(150, 200);
[mySwitch addTarget:self action:@selector(switched:)
forControlEvents:UIControlEventValueChanged];
}
```
### 在 ViewController.m 中修改 viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addSwitch];
}
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出

向右滑動開關輸出如下所示

## IOS滑塊的使用
滑塊用于從某個范圍的值里選擇的一個值。
重要的屬性
* continuous
* maximumValue
* minimumValue
* value
### 重要的方法
```
- (void)setValue:(float)value animated:(BOOL)animated
```
### 添加自定義方法 addSlider 和 sliderChanged
```
-(IBAction)sliderChanged:(id)sender{
NSLog(@"SliderValue %f",mySlider.value);
}
-(void)addSlider{
mySlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 200, 200, 23)];
[self.view addSubview:mySlider];
mySlider.minimumValue = 10.0;
mySlider.maximumValue = 99.0;
mySlider.continuous = NO;
[mySlider addTarget:self action:@selector(sliderChanged:)
forControlEvents:UIControlEventValueChanged];
}
```
### 在 ViewController.m 中修改 viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addSlider];
}
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出

當拖動滑塊效果如下:

## IOS警告對話框的使用
警告對話框用來給用戶提供重要信息。
僅在警告對話框視圖中選擇選項后,才能著手進一步使用應用程序。
### 重要的屬性
* alertViewStyle
* cancelButtonIndex
* delegate
* message
* numberOfButtons
* title
### 重要的方法
```
- (NSInteger)addButtonWithTitle:(NSString *)title
```
```
- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex
```
```
- (void)dismissWithClickedButtonIndex:
(NSInteger)buttonIndex animated:(BOOL)animated
```
```
- (id)initWithTitle:(NSString *)title message:
(NSString *)message delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString*)otherButtonTitles, ...
```
```
- (void)show
```
### 更新 ViewController.h,如下所示
讓類符合警告對話框視圖的委托協議,如下所示,在ViewController.h中添加<UIAlertViewDelegate>
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIAlertViewDelegate>{
}
@end
```
### 添加自定義方法 addAlertView
```
-(void)addAlertView{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
@"Title" message:@"This is a test alert" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
[alertView show];
}
```
### 執行警告對話框視圖的委托方法
```
#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:
(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
NSLog(@"Cancel button clicked");
break;
case 1:
NSLog(@"OK button clicked");
break;
default:
break;
}
}
```
### 在 ViewController.m 中修改 viewDidLoad,如下所示
```
(void)viewDidLoad
{
[super viewDidLoad];
[self addAlertView];
}
```
### 輸出
現在當我們運行該應用程序我們會看到下面的輸出:

## IOS圖標的使用
IOS圖標是用于應用程序相關的操作。
IOS 中的不同圖標
* AppIcon
* App Store 的應用程序圖標
* 搜索結果和設置的小圖標
* 工具欄和導航欄圖標
* 選項卡欄圖標
### AppIcon
AppIcon 是出現在設備SpringBoard (默認屏幕上的所有的應用程序) 的應用程序的圖標。
### App Store 的應用程序圖標
它是512 x 512 或 1024 x 1024(推薦大小)的高分辨率的應用程序圖標。
### 搜索結果和設置的小圖標
在搜索列表的應用程序中使用這個小圖標。
它還用于與相關的應用程序的功能是啟用和禁用的設置屏幕上。如:啟用定位服務。
### 工具欄和導航欄圖標
工具欄和導航欄中使用特制的標準圖標的列表。它包括的份額,像圖標相機,撰寫等等。
### 選項卡欄圖標
選項卡欄中使用一系列特制的標準圖標列表。它包括的圖標有書簽、 聯系人、 下載等。
有的不同的 iOS 設備的每個圖標大小的都不一樣。你可以查看更多關于蘋果文件中圖標的準則:[ios人機交互界面指南](//developer.apple.com/library/ios/#documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html)。<split>
# IOS加速度傳感器(accelerometer)
## 簡介
加速度傳感器是根據x、y和z三個方向來檢測在設備位置的改變。
通過加速度傳感器可以知道當前設備相對于地面的位置。
以下實例代碼需要在真實設備上運行,在模擬器上是無法工作的。
### 實例步驟
1、創建一個簡單的視圖應用程序
2、在ViewController.xib中添加三個標簽,并創建一個ibOutlets分別為:xlable、ylabel和zlabel
3、如下所示,更新ViewController.h
```
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIAccelerometerDelegate>
{
IBOutlet UILabel *xlabel;
IBOutlet UILabel *ylabel;
IBOutlet UILabel *zlabel;
}
@end
```
4、如下所示,更新ViewController.m
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIAccelerometer sharedAccelerometer]setDelegate:self];
//Do any additional setup after loading the view,typically from a nib
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
(UIAcceleration *)acceleration{
[xlabel setText:[NSString stringWithFormat:@"%f",acceleration.x]];
[ylabel setText:[NSString stringWithFormat:@"%f",acceleration.y]];
[zlabel setText:[NSString stringWithFormat:@"%f",acceleration.z]];
}
@end
```
### 輸出
當我們在iPhone設備中運行該應用程序,得到的輸出結果如下所示。
