iOS SDK:創(chuàng)建一個動態(tài)的Action Sheet
Step 1:創(chuàng)建新項目
打開Xcode,選擇“Create a new Xcode project”,選擇“Single View Application”,點擊 “next”。輸入項目名稱(我這么命名為“Fruits”),并確定Devices中選擇的是iPhone,然后勾選上 “Use Storyboards”和“Use Automatic Reference Counting”,并點擊“Next”,選擇存放項目的地 方,再點擊“create”。
Step 2: 設定支持的方向
我只想讓程序支持縱向模式,所以到 “Supported Interface Orientations”中,取消橫向模式的選中。
Step 3: 創(chuàng)建界面
打開工程的Storyboard文件,從 Object Library中拖一個label到View Controller,將這個lable放在 View Controller的頂端,并居中,且寬度設置為280像素。打開Attributes Inspector(屬性面板),將對其方式設置為 居中,***,刪除lable中的默認文本。
接著,從Object Library拖一個按鈕到View Controller中,將這個按鈕放在label下邊,雙擊按鈕的標題,并將標題改為“Fruits”。
Step 4:連接IBOutlet
打開ViewController.m,按照如下代碼代碼進行修改:
- #import "ViewController.h"
- @interface ViewController () <UIActionSheetDelegate>
- @property(nonatomic, weak) IBOutlet UILabel *fruitLabel;
- @property(nonatomic, strong) NSMutableArray *fruits;
- - (IBAction)showFruits:(id)sender;
- @end
在上面的代碼中,為label創(chuàng)建了一個插槽(outlet),以及一個存儲fruit的可變數(shù)組,還創(chuàng)建一個action用來顯示 “action sheet”。我們還添加了UIActionSheetDelegate,所以當你從action sheet中選擇一個fruit的 時,我們就可以更新label。
注意,上面所有這些內容都是在類擴展中實現(xiàn)的——因為這些屬性和方法沒不需要暴露給別的類。
現(xiàn)在已經建立好了outlet和action,現(xiàn)在我們只需要將它們連接到相應的控件中就可以了。打開Storyboard,將 fruitsLabel outlet與lable進行連接,以及把showFruits:action和button進行連接。為選擇 Touch Up Inside作為按鈕的控件事件。
Step 5: 創(chuàng)建水果列表
打開ViewController.m,創(chuàng)建下邊這樣一個初始化方法:
- -(id) initWithCoder:(NSCoder *)aDecoder{
- if (self = [super initWithCoder:aDecoder]) {
- self.fruits = [[NSMutableArray alloc] initWithObjects:@"Apple", @"Orange", @"Banana", @"Strawberry", @"Peach",nil];
- }
- return self;
- }
上面的代碼中創(chuàng)建了一個水果數(shù)組,并在這個數(shù)組中存儲了一些水果。
Step 6: 顯示列表
在didReceiveMemoryWarning方法后面添加如下代碼:
- - (IBAction)showFruits:(id)sender
- {
- UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select a fruit"
- delegate:self
- cancelButtonTitle:nil
- destructiveButtonTitle:nil
- otherButtonTitles:nil];
- for (NSString *fruit in self.fruits) {
- [actionSheet addButtonWithTitle:fruit];
- }
- actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
- [actionSheet showInView:self.view];
- }
上面的代碼首先創(chuàng)建一個action sheet,在初始化方法中,我們傳遞了一個標題和一個delegate,但是我們沒有添加任何按鈕,甚至是一個取消按鈕。如果我們在這里添加一個取消按鈕,然后再添加其它按鈕,那么取消按鈕就會在列表的最上邊,而不是最下面。
接下來,使用一個for in循環(huán)語句來遍歷之前創(chuàng)建的水果數(shù)組,再這個循環(huán)語句中,我們將所有的水果添加為action sheet的按鈕。循環(huán)語句之 后,給action sheet添加了一個cancel按鈕——通過給cancelButtonIndex添加一個標題為“Cancel”的按鈕。這 樣,action sheet就知道取消按鈕應該位于列表的底部,***,我們以正常的方式將action sheet顯示出來。
Step 7:更新Fruits Label
在showFruits: action下方添加一個action sheetdelegate協(xié)議。
- - (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- if (buttonIndex != actionSheet.cancelButtonIndex) {
- self.fruitLabel.text = [self.fruits objectAtIndex:buttonIndex];
- }
- }
當點擊action sheet中的按鈕時,就會調用上的delegate方法,在方法中,首先判斷一下被按下的按鈕是取消按鈕還是fruit的按鈕——通 過對選中按鈕的索引值和取消按鈕的索引值進行比較來判斷的。如果選中的是fruit相關按鈕,那么就將label更新為選中的水果。