iOS開發UI組件整理

jopen 9年前發布 | 30K 次閱讀 IOS iOS開發 移動開發

iOS開發UI組件整理

作者: 神獸gcc

最近把iOS里的UI組件重新整理了一遍,簡單來看一下常用的組件以及它們的實現。其實現在這些組件都可以通過Storyboard很快的生成,只是要向這些組件能夠變得生動起來并且賦予它們更具生命力的事件,還是需要一番功夫的。

UIButton

這兒有一篇教程,挺全的,可以參考下: http://www.cnblogs.com/chen1987lei/archive/2011/09/09/2172757.html

這個就不多說了,對照官方的文檔也可以更多的去學習。插一句題外話,在學這些組件的時候,最令人頭疼的不是你搞不定一個組件的某個屬性或者方法,而是你壓根兒不知道有這個東西。所以在學習這些組件的時候最好的方式還是通過官方文檔,雖然已開始可能有些困難,但是硬著頭皮去啃,就一定會有悟道的那一天。建議有問題先去看文檔,如果實在不行再去Google啊,Stack Overflow啊神馬的。

UIAlertController

彈出式的提示框。現在市面上的書籍包括網上的一些資料都還停留在iOS8之前的時代,那個時候的彈出框是一個叫做UIAlertView的東西,但是現在,在XCode7和iOS9的時代,你會發現這個東西被棄用了。蘋果自iOS8開始,廢除了UIAlertView而改用UIAlertController來控制提示框。

來看看UIAlertController的實現吧,下面這個程序是我在練習UITableView時的代碼,實現了一個類似與通訊錄的東西,我們抓住主要矛盾,來看點擊某一行cell后,彈出的消息提示框是怎么實現的。以下代碼在ViewController.m中實現。

//創建提示框窗口
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"System Info" message:[contact getName] preferredStyle:UIAlertControllerStyleAlert];
//實例化取消按鈕  
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    //點擊取消按鈕后控制臺打印語句。
    NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
}];
//實例化確定按鈕   
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    //下面這段代碼不用管它,簡單點講就是獲取當前行的一個字符串。
    UITextField *textfield = alertController.textFields[0];
    KCContactGroup *group = _contacts[_selectedIndexPath.section];
    KCContact *contact = group.contacts[_selectedIndexPath.row];
    contact.phoneNumber = textfield.text;
    NSArray *indexPaths = @[_selectedIndexPath];
    [_tableview reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
}];
//向彈出框中添加按鈕和文本框
[alertController addAction:cancelAction];
[alertController addAction:otherAction];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    // 可以在這里對textfield進行定制,例如改變背景色等
    textField.text = contact.phoneNumber;
}];
//將提示框彈出
[self presentViewController:alertController animated:YES completion:nil];

實現了大概就是這個樣子,文本框里的東西是從cell里面提取的。

iOS開發UI組件整理

這里還有一句題外話要講。網上是沒有任何關于最新的UIAlertController的使用教程的,我自己用了整整一個下午看官方文檔一步一步調試才實現了這個惱人的提示框。官方的文檔真的是個好東西,越用越強大!!

UISegmentedControl

分段控件,就是一欄按鈕集成在一排里。很簡單,就像Button一樣。這個樣子的:

iOS開發UI組件整理

UISwtich

按鈕控件,手機里開飛行模式的那個東西。通過Storyboard可以很快很方便的建立,不要忘了關聯起來就好。

這里簡單講一下它的純代碼實現,其實包括上面的UISegmentedControl,還有下面的一些簡單控件它們手寫實現的方法都是一樣的。截張圖給大家說明一下就好了,都是一樣的,后面的類似的控件也不多啰嗦了。

iOS開發UI組件整理

UISlider

進度條型的選擇控件,對應數值,可以進行設置音量等操作,根據官方文檔可以看到很多關于它的設置,基本實現同上。

UIPageControl

這是個好東西。

這是個好東西。

這是個好東西。

重要的事情說三遍。個人認為,它雖然很小,但絕對逼格夠高,搭配UIScrollView,絕對讓你的界面高端起來。

關于這個的代碼不小心被我刪掉了,沒法給大家展示,不過過幾天我會用這個做一個APP的歡迎界面,到時候再展示咯。

UITextField

簡單控件,可以參考先前的傳值操作(傳送門: iOS開發——從一道題看Delegate ),基本上把這個的用法實現的差不多了,要想更多地設置它————官方文檔見。

UIDatePicker

顧名思義,日期選擇控件。實現同上。

UIScrollView

有的時候呢,我們的照片,或者圖片會很大,而允許我們輸出的窗口卻不夠大,那么我們就需要這個家伙來幫忙了,它可以讓一張圖片在一個視圖里滾動展示,效果類似于。。。做B超?(天,怎么會有這種腦洞大開的比喻)

大概就是這樣整的:

iOS開發UI組件整理

UITextView

還是一個可編輯文本框,與先前的UITextField不同的是,這個可以顯示更多行的內容,還可以對他進行編輯的監控,通過代理方法,我們可以獲取該文本框中的內容,在實際的應用中,發布什么長微博啊,文本啊,都能用到它。

這里實現沒什么好說的,主要來看看它的幾個代理方法:

iOS開發UI組件整理

UIToolbar

開發中經常會用到的控件之一,實現起來也很簡單,與此同時我們還要知道 UIBarButtonItem 和 Fixed Space Bar Button Item,這兩個小東西是在Bar上的按鈕和間距,都被對象化了。

來看代碼:

#import "ViewController.h"
@interface ViewController ()
//聲明
@property (nonatomic, strong) UIToolbar *mytoolbar;
@end
@implementation ViewController

  • (void)viewDidLoad { [super viewDidLoad]; //實例化 self.mytoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 30)]; //添加到視圖 [self.view addSubview:self.mytoolbar]; //選擇風格,這里我們選擇黑色風格 self.mytoolbar.barStyle = UIBarStyleBlack; //添加按鈕和按鈕之間的間距,這些都被對象化了,按鈕是可以實現方法的 UIBarButtonItem item1 = [[UIBarButtonItem alloc]initWithTitle:@"hello" style:UIBarButtonItemStylePlain target:self action:@selector(sayhello)]; UIBarButtonItem fixed = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"bye" style:UIBarButtonItemStylePlain target:self action:@selector(saybye)]; //實例化的UIToolbar里面有items屬性,是一個數組,用來存放我們要加上去的按鈕 self.mytoolbar.items = @[item1, fixed, item2]; } //點擊item要實現的方法,輸出hello或者bye
  • (IBAction)sayhello{ NSLog(@"hello"); }
  • (IBAction)saybye{ NSLog(@"bye"); }
  • (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end</pre>

    UIPickerView

    與前面的時間選擇類似,只不過這個你可以自己設置內容。

    UITableView

    BOOM!

    強大,異常強大。不多說,我推薦看 iOS開發系列--UITableView全面解析 這篇文章,寫得很棒。

    我自己也把大部分的學習時間用在了它的學習上,至今為止我覺得我還沒能真正做到熟練地使用它,等以后成熟了,再寫吧。

    UICollectionView

    又是一個龐大的家伙,在很多壁紙類APP中我們可以看到它的影子。

    關于它的實現,我總結為以下幾步:

    • .h文件聲明代理和數據源

    • .m文件具體實現

      • 聲明UICollectionView

      • 實例化,包括設置大小,位置,顏色等等

      • 加載代理和數據源到實例化的view

      • 注冊cell(這里需要)

      • 將實例化的UICollectionView加入到View中

      • 實現數據源方法(包括必須實現的和選擇實現的)

      • 實現代理方法(包括必須實現的和選擇實現的)

      </ul>

      關于數據源方法和代理方法,在這里需要特別說明一下,我們還是會出現不知道這個數據源或者代理中到底有什么的困惑,我們要command進去這些代理或者數據源去發現和尋找,文檔還是我們學習的最終歸宿。

      按照上面的步驟,實現代碼:

      #import "ViewController.h"
      @interface ViewController ()
      @property (nonatomic, strong) UICollectionView collectionView;
      @end
      static NSString cid = @"cid";
      @implementation ViewController
      
    • (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init]; CGRect flame = CGRectMake(20, 40, self.view.frame.size.width-40, self.view.frame.size.height-60); self.collectionView = [[UICollectionView alloc]initWithFrame:flame collectionViewLayout:flowlayout]; self.collectionView.dataSource = self; self.collectionView.delegate = self; [self.view addSubview:self.collectionView]; //注冊cell [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cid]; }
    • (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return 50; } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
    • (UICollectionViewCell )collectionView:(UICollectionView )collectionView cellForItemAtIndexPath:(NSIndexPath )indexPath{ UICollectionViewCell cell = [collectionView dequeueReusableCellWithReuseIdentifier:cid forIndexPath:indexPath]; cell.backgroundColor = [UIColor blueColor]; return cell; }
    • (UIEdgeInsets)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(10, 10, 10, 10); }
    • (CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return CGSizeMake(120, 100); }
    • (void)collectionView:(UICollectionView )collectionView didSelectItemAtIndexPath:(NSIndexPath )indexPath{ UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; cell.backgroundColor = [UIColor yellowColor]; NSLog(@"%ld",indexPath.row); }
    • (void)collectionView:(UICollectionView )collectionView didDeselectItemAtIndexPath:(NSIndexPath )indexPath{ UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; cell.backgroundColor = [UIColor blueColor]; }
    • (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end</pre>

      UIViewController

      接下來我們來聊聊ViewController。視圖控制器在我們開發中最重要的 MVC模式 中扮演著重要的角色,作為顯示和數據的調度者,它的存在決定了我們的程序到底以怎樣的形式呈現在用戶面前。

      這個最基礎的Controller就不多說了,在目前的XCode中,一般來說新建的第一個Single View就是用的這個。

      UINavigationController

      很重要的一個東西。導航視圖控制器。說簡單點它就是一個來存放視圖的棧,原則上先進后出,一層一層的來管理在它里面的視圖。在學習它的過程中還要掌握UINavigationBar、UINavigationitem等控件,還要熟悉幾個pop、push方法。

      既然是導航視圖控制器,導航自然不是導的一個視圖,而是管理多個視圖,實現的時候有很多需要注意的地方,我們一步一步的來看。

      首先新建一個工程,我們要純手寫代碼來搞定之。

      第一步,建立我們需要管理的多個視圖。

      “command+N”新建Cocoa Touch Class,命名為myViewController,Subclass of選擇為UIViewController,重復四次,我們獲得了四個試圖控制器,也就是四個視圖,接下來我們將用導航視圖控制器來管理它們。

      第二步,初始界面設置

      在這里,我們需要來到AppDelegate.m文件,來配置初始界面,自定義- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法。

      代碼如下:

      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
        //獲取屏幕大小
        UIScreen *screen = [UIScreen mainScreen];
        //初始化窗口
        self.window = [[UIWindow alloc]initWithFrame:screen.bounds];
        //將視圖1設置為初始視圖
        myViewController1 *vc1 = [[myViewController1 alloc]init];
        //來個背景顏色區分一下
        vc1.view.backgroundColor = [UIColor blueColor];
        //實例化導航視圖控制器并添加視圖1進來
        UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc1];
        //將導航視圖控制器設置為窗口根視圖
        self.window.rootViewController = nc;
        //設置窗口可見
        [self.window makeKeyAndVisible];
        return YES;
      }

      第三步,配置各個視圖

      我們要在第一個視圖中實例化第二個視圖,并通過某種方式,使用UINavigationController跳轉到第二個視圖;在第二個視圖中實例化第三個視圖,以此類推直到最后一個視圖。當然,我們也可以選擇直接跳到某個你想要去的視圖,比如從第四個視圖跳到第一個或者第二個。

      我們現在視圖一中添加一個按鈕,添加一個點擊按鈕的事件,注意,我們就是通過這個事件方法來實現頁面的跳轉的,myViewController1.m代碼:

      #import "myViewController1.h"
      #import "myViewController2.h"
      @interface myViewController1 ()
      @end
      @implementation myViewController1
    • (void)viewDidLoad { [super viewDidLoad]; //設置視圖二樣式,添加一個按鈕,點擊觸發事件,跳轉到下一頁面 UIButton btn = [UIButton buttonWithType:UIButtonTypeSystem]; [btn setTitle:@"GO" forState:UIControlStateNormal]; btn.frame = CGRectMake(160, 100, 30, 36); [btn addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; UILabel lable = [[UILabel alloc]initWithFrame:CGRectMake(160, 160, 100, 36)]; lable.text = @"第一頁"; [self.view addSubview:lable]; } //這里才是實現頁面跳轉的重點!!!! -(IBAction)go:(id)sender{ myViewController2 *vc2 = [[myViewController2 alloc]init]; vc2.view.backgroundColor = [UIColor greenColor]; //看這里!!!!!push方法將視圖一推向視圖二 [self.navigationController pushViewController:vc2 animated:YES]; }
    • (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. }</pre>

      類似的,我們編寫myViewController2.m,myViewController3.m,myViewController4.m的代碼。我們稍微修改一下myViewController4.m中的go方法,讓視圖四直接跳到視圖二:

      -(IBAction)go:(id)sender{
        //[self.navigationController popViewControllerAnimated:YES];    pop方法跳回前一視圖
        //[self.navigationController popToRootViewControllerAnimated:YES];  popToRoot方法直接跳回第一視圖 
        NSArray *controllers = self.navigationController.viewControllers; 
        //popToViewController方法,我們可以選擇要跳到的視圖
        [self.navigationController popToViewController:[controllers objectAtIndex:1] animated:YES];
      }

      UITabbarController

      區別于UINavigationController的頂部導航,UITabbarController是底部導航,功能上差不多,可以直接切換多個視圖,典型的應用非常多,微信,QQ都是,實現起來也是類似于上面的UINavigationController。

      可以參考這篇資料: iOS開發UI篇—UITabBarController簡單介紹

      簡單地總結到這里,只是很簡單的實現,日后通過文檔再慢慢地學習更深層次的內容。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!