iOS開發-分頁欄和選取器的使用


一、分頁欄

創建一個新的項目,Subclass of的值選中UIViewController,然后在storyboard中刪除根視圖,在右下方拖出一個Tab Bar Controller

新增分頁,只需從右下方拖出一個普通的View Controller,按住鼠標右鍵從分頁欄控制器拖動到新視圖控制器上釋放,在彈出面板中的Relationship Segue標題下選中view controllers,使用這些分頁要給他們創建Cocoa Touch Class 並關聯。

 

設置分頁欄底部的標題與圖標,如圖:

 

 

 

 

二、選取器

選取器分為Date Picker和Picker View,前者是日期選取器,后者為一般選取器,可以任意定制用途。

 

(一)下面實現一個功能:點擊按鈕,彈出一個警告視圖顯示當前在日期選取器中選定的日期和時間

1)往Date分頁上拖出一個Date Picker和一個按鈕,並設置約束

 

2)創建日期選取器的輸出接口,選中Date Picker,按住右鍵拖動到實現文件,創建一個名為datePicker的輸出接口,如圖:

 

 

3)加載此視圖時,選取器都會重置為當前的日期和時間的實現代碼,在viewDidLoad方法中編寫,如圖:

 

 

 

4)實現功能的操作方法,選中按鈕,按住右鍵拖動到實現文件下方,創建一個名為buttonPressed的操作方法,並編寫代碼,如圖:

 

5)實現效果,顯示的是格林威治標准時間

 

(二)自定義的選取器視圖的實現,下面記錄幾個要點,與上面相同的步驟就不說了

1)將控制器實現為數據源和委托,關聯dateSource和delegate,如圖:

 

 

2)在.h文件中添加協議

 

 

 

3)創建一個數組,用於向選取器提供數據,並將其賦給characterNames屬性,代碼如下:

 

4)按鈕的方法和數據源、委托的方法實現,結合上下圖

 

5)實現效果

 

(三) 實現多滾輪選取器

1)添加委托與數據源協議,與上面相同。

<UIPickerViewDelegate,UIPickerViewDataSource>

 

2)定義兩個選取器滾輪相應的索引值常量,以及相應的兩個數組

 

 

 

3)其他方法的實現跟一個選取器差不多,這里只是多了一個判斷使用哪個滾輪,代碼如下:

@implementation DoubleComponentPickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 初始化滾輪的內容
    self.fillingTypes = @[@"Ham",
                       @"Turkey",
                       @"Peanut Butter",
                       @"Tuna Salad",
                       @"Chicken Salad",
                       @"Roast Beef",
                       @"Vegemite"];
    self.breadTypes = @[@"White",
                        @"Whole Wheat",
                        @"Rye",@"Sourdough",
                        @"Seven Grain"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}
- (IBAction)buttonPressed:(id)sender {
    NSInteger fillingRow = [self.doublePicker selectedRowInComponent:kFillingComponent];
    NSInteger breadRow = [self.doublePicker selectedRowInComponent:kBreadComponent];
    
    NSString *filling = self.fillingTypes[fillingRow];
    NSString *bread = self.breadTypes[breadRow];
    
    NSString *message = [[NSString alloc] initWithFormat:@"Your %@ on %@ bread will be right up.",filling,bread];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Thank you for your order" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Great!" style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}


#pragma mark Picker Data Soure Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    // 滾輪數目2個
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == kBreadComponent) {
        return [self.breadTypes count];
    }else{
        return [self.fillingTypes count];
    }
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == kBreadComponent) {
        return self.breadTypes[row];
    }else{
        return self.fillingTypes[row];
    }
}

@end

 

 

 

 

 

 

4)運行效果

 

 

 

(四)實現有依賴關系的選取器,即其中的內容變化會引起另一個中的內容變化

 

由於步驟大同小異,這里只po代碼了。。。

//
//  DependentComponentPickerViewController.m
//  Pickers
//
//  Created by  Jierism on 16/7/19.
//  Copyright © 2016年  Jierism. All rights reserved.
//

#import "DependentComponentPickerViewController.h"

#define kStateComponent 0
#define kZipComponent 1

@interface DependentComponentPickerViewController ()
@property (weak, nonatomic) IBOutlet UIPickerView *dependentPicker;
@property (strong,nonatomic) NSDictionary *stateZips;
@property (strong,nonatomic) NSArray *states;
@property (strong,nonatomic) NSArray *zips;


@end

@implementation DependentComponentPickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSBundle *bundle = [NSBundle mainBundle];
    NSURL *plistURL = [bundle URLForResource:@"statedictionary" withExtension:@"plist"];
    
    self.stateZips = [NSDictionary dictionaryWithContentsOfURL:plistURL];
    
    NSArray *allStates = [self.stateZips allKeys];
    NSArray *sortedStates = [allStates sortedArrayUsingSelector:@selector(compare:)];
    self.states = sortedStates;
    
    NSString *selectedState = self.states[0];
    self.zips = self.stateZips[selectedState];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)buttonPressed:(id)sender {
    NSInteger stateRow = [self.dependentPicker selectedRowInComponent:kStateComponent];
    NSInteger zipRow = [self.dependentPicker selectedRowInComponent:kZipComponent];
    
    NSString *state = self.states[stateRow];
    NSString *zip = self.states[zipRow];
    
    NSString *title = [[NSString alloc] initWithFormat:@"You selected zip code %@.",zip];
    NSString *message = [[NSString alloc] initWithFormat:@"%@ is in %@",zip,state];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}



#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == kStateComponent) {
        return [self.states count];
    }else{
        return [self.zips count];
    }
}

#pragma mark Picker Delegate Methods

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == kStateComponent) {
        return self.states[row];
    }else{
        return self.zips[row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == kStateComponent) {
        NSString *selectedState = self.states[row];
        self.zips = self.stateZips[selectedState];
        [self.dependentPicker reloadComponent:kZipComponent];
        [self.dependentPicker selectRow:0 inComponent:kZipComponent animated:YES];
    }
}

// 調整選取器占用的寬度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    CGFloat pickerWidth = pickerView.bounds.size.width;
    if (component == kZipComponent) {
        return pickerWidth/3;
    }else{
        return 2*pickerWidth/3;
    }
}

@end

 

 

注意這里加入了一個.plist文件,涉及到包的使用。什么是包?

包(bundle )是一種特定類型的文件夾,其中的內容遵循特定的結構。應用程序和框架都是包,這個調用返回的包對象表示我們的應用程序。

 

 

(五)用選取器實現的滾輪小游戲

相同的內容也不說了,詳見代碼

 

1)接口的聲明,這里還添加了游戲聲音

 

2)往選取器里面加載圖片

 

3)實現點擊按鈕,選取器開始滾動,並在滾動過程中隱藏按鈕

- (void)showButton {
    self.button.hidden = NO;
}

- (IBAction)spin:(id)sender {
    
    BOOL win = NO;
    int numInRow = 1;
    int lastVal = -1;
    for (int i = 0; i < 5 ; i++) {
        int newValue = arc4random_uniform((uint)[self.images count]);
        if (newValue == lastVal) {
            numInRow++;
        }else{
            numInRow = 1;
        }
        lastVal = newValue;
        
        [self.picker selectRow:newValue inComponent:i animated:YES];
        [self.picker reloadComponent:i];
        if (numInRow >= 3) {
            win = YES;
        }
    }
    
    if (_crunchSoundID == 0) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"crunch" ofType:@"wav"];
        NSURL *soundURL = [NSURL fileURLWithPath:path];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &_crunchSoundID);
    }
    
    AudioServicesPlaySystemSound(_crunchSoundID);
    if (win) {
        [self performSelector:@selector(playWinSound) withObject:nil afterDelay:0.5];
    }else{
        [self performSelector:@selector(showButton) withObject:nil afterDelay:0.5];
    }
    
    // 隱藏按鈕
    self.button.hidden = YES;
    self.winLabel.text = @" ";
}

 

 

 

4)播放聲音的方法,點擊按鈕和獲勝時會被調用,播放相應的音樂

 

5)數據源協議和委托的方法

 

6)運行效果

 


免責聲明!

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



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