1. 程式人生 > >學習ios之高階控制元件和協議(資料來源協議和委託協議)

學習ios之高階控制元件和協議(資料來源協議和委託協議)

一、選擇器
ios的選擇器分的比較清楚,分為時間選擇器和自定義的選擇器,先說說時間選擇器吧,比較簡單
1、時間選擇器
這裡寫圖片描述

這裡寫圖片描述

直接看程式碼,所有介紹都在程式碼中

    var datePicker:UIDatePicker!
    var label:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let frame=UIScreen.main
.bounds let xMargin:CGFloat=20 //初始化時間選擇器 self.datePicker=UIDatePicker.init(frame: CGRect(x: xMargin,y: 20,width: frame.size.width-2*xMargin,height: 170 )) //時間顯示模式 這裡選擇日期和時間 還有時間模式、日期模式、計時器模式 self.datePicker.datePickerMode=UIDatePickerMode.dateAndTime //設定本地化設定 顯示為簡體中文 self.datePicker
.locale=Locale(identifier: "zh-Hans") self.view.addSubview(self.datePicker) //初始化label 顯示選擇的時間 self.label=UILabel.init(frame: CGRect(x: xMargin,y: frame.size.height/2, width: frame.size.width-2*xMargin,height: 31)) self.label.textAlignment=NSTextAlignment.center self.view
.addSubview(self.label) //初始化一個UIButton 點選button 讓label顯示當前的時間 let button=UIButton.init(type: UIButtonType.system) button.frame=CGRect(x: (frame.size.width-70)/2, y: self.label.frame.origin.y+30,width: 70,height: 31) button.setTitle("click me", for: UIControlState.normal) button.addTarget(self, action: #selector(ViewController.showTime(sender:)), for: UIControlEvents.touchUpInside) self.view.addSubview(button) } func showTime(sender:Any) { let date:Date=self.datePicker.date //獲取時間以本地化的語言描述 返回一個字串 let des=date.description(with: NSLocale.current) NSLog("當前的時間%@",des) //時間格式化工廠 跟android中的基本一樣 let format:DateFormatter=DateFormatter() format.dateFormat="YYYY-MM-dd HH:mm:ss" self.label.text=format.string(from: date) }

2、普通選擇器(自定義選擇器資料)
自定義選擇器需要有資料來源,這裡我們使用plist檔案,先看怎麼匯入plist檔案
這裡寫圖片描述

下面可以點選options,選擇複製到專案內

這裡寫圖片描述

很簡單,需要注意的是,注意plist檔案的root是什麼型別,是Array 還是 Dictionary,然後使用相應的NSArray 或者 NSDictionary 把檔案內容讀取到陣列或者字典中去

這裡寫圖片描述

我們看專案最終效果:

這裡寫圖片描述

//
//  ViewController.swift
//  P5.1UIPicker
//
//  Created by LF on 2017/4/2.
//  Copyright © 2017年 yinwei. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {

    var pickView:UIPickerView!
    var name:UILabel!

    var pickerData:NSArray!
    var pickerProvincesData:NSMutableArray!
    var pickerCitiesData:NSMutableArray!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //初始化選擇器的資料來源 這裡的plist檔案是自己在網上下的
        let plistPath=Bundle.main.path(forResource: "ProvincesAndCities", ofType: "plist")

        //注意這裡的根Root是Array 有的可能是 dictionary
        let dic=NSArray.init(contentsOfFile: plistPath!)

        self.pickerData=dic

        //省份名資料
        //使用可變陣列 後面為遍歷提供方便可以直接新增新的元素資料到陣列中去
         self.pickerProvincesData=NSMutableArray.init()
        //遍歷pickerData把省份儲存到陣列中
        for province in pickerData {

        //province是字典型別 然後取出 key 為State的就是省份
        self.pickerProvincesData.add((province as! NSDictionary).value(forKey: "State") as! String)

        }


        //顯示的第一條資料

        let cityesDic=(self.pickerData[0] as! NSDictionary).value(forKey: "Cities") as! NSArray

        self.pickerCitiesData=NSMutableArray.init()

        for city in cityesDic {
        //city為字典型別,取出key 為city的值 即為城市名稱
        self.pickerCitiesData.add((city as! NSDictionary).value(forKey: "city") as! String)
        }


        //初始化UIPickerView
        let frame=UIScreen.main.bounds
        let xSpace:CGFloat=27
        let ySpace:CGFloat=77
        self.pickView=UIPickerView.init(frame: CGRect(x: xSpace,y: ySpace,width: frame.size.width-2*xSpace,height: 170))


        self.view.addSubview(self.pickView)


        //繫結協議
        self.pickView.dataSource=self
        self.pickView.delegate=self

        //初始化一個UILabel
        self.name=UILabel.init(frame: CGRect(x: xSpace, y: 300 ,width: frame.size.width-2*xSpace,height: 31))
        self.name.textAlignment=NSTextAlignment.center
        self.view.addSubview(self.name)

        //初始化一個UIButton
        let button=UIButton.init(type: UIButtonType.system)
        button.frame=CGRect(x: (frame.size.width-70)/2,y: 330,width: 70,height: 31)
        button.setTitle("click me", for: UIControlState.normal)
        button.addTarget(self, action: #selector(ViewController.showSelected(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(button)

    }

    func showSelected(sender:Any) {

        let row1=self.pickView.selectedRow(inComponent: 0)
        let row2=self.pickView.selectedRow(inComponent: 1)
        let pro=self.pickerProvincesData[row1] as! String
        let city=self.pickerCitiesData[row2] as! String
        self.name.text=String.init(format: "%@ %@市", pro,city)


    }



    //選擇器的拔輪的行數
    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 2
    }

    //選擇器中某個拔輪的行數
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if(component==0){

           return self.pickerProvincesData.count
        }

        return self.pickerCitiesData.count
    }


    //委託協議
    //為選擇器的某個拔輪提供顯示資料
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if(component==0){

            return self.pickerProvincesData[row] as? String

        }

        return self.pickerCitiesData[row] as? String
    }
    //選中選擇器的某個拔輪時呼叫
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        //選中省份時確定城市拔輪的資料
        if(component==0){

            let cityesDic=(self.pickerData[row] as! NSDictionary).value(forKey: "Cities") as! NSArray

            //清空城市陣列
            self.pickerCitiesData.removeAllObjects()

            for city in cityesDic {

                self.pickerCitiesData.add((city as! NSDictionary).value(forKey: "city") as! String)
            }

            self.pickView.reloadComponent(1)

        }


    }


}

所有內容都在程式碼中了,比較詳細了,應該可以看得懂,不在贅述了

二、UIColoctionView 集合檢視
集合檢視就像我們看小說時的那種 書架 型別 ,分 一行 一行的 ,每行上面都有幾本書
每一行 在集合檢視中 也叫作節
每本書 叫做單元格了
這裡面主要學習UIColoctionView 檢視如何建立和如何使用它的相關的協議
看效果圖
這裡寫圖片描述

我設定的資料比較簡單,就是7條資料,一節兩條資料
詳細都在程式碼中註釋了
首先為每個單元格 綁定了一個類 projectMy 相當於android中 介面卡中的集合或者陣列的類

import Foundation

//建立格簡單的類,相當於android中介面卡的資料類
class ProjectMy {

    var name:String
    var description:String
    init(name:String,description:String) {
        self.name=name
        self.description=description
    }

}

建立自定義單元格樣式,相當於Android中的item檢視

import UIKit

//建立單元格  相當於 android中的 item 佈局檔案
class ProCollectionViewCell: UICollectionViewCell {

    var name:UILabel!
    var details:UITextView!

    override init(frame: CGRect) {
        super.init(frame:frame)

        //獲取單元格的大小
        let size:CGSize=self.frame.size

        //初始化name
        self.name=UILabel.init(frame: CGRect(x: 0, y: size.height-31, width: size.width,height: 31))
        self.name.textAlignment=NSTextAlignment.center
        self.addSubview(self.name)

        //初始化
        self.details=UITextView.init(frame: CGRect(x: 0, y: 0,width: size.width, height: size.height-31))
        self.details.textAlignment=NSTextAlignment.left
        self.details.isEditable=false //設定不可編輯
        self.addSubview(self.details)



    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder) has not been implemented")
    }

}

看controller檔案

//
//  ViewController.swift
//  P5UIColection
//
//  Created by LF on 2017/4/2.
//  Copyright © 2017年 yinwei. All rights reserved.
//

import UIKit

//實現 集合檢視委託協議 UICollectionViewDelegate 和 資料來源協議UICollectionViewDataSource
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    var pros:Array<ProjectMy>!

    var coloction:UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //建立模擬資料
        let p=ProjectMy.init(name: "健身", description: "好好鍛鍊,長出八塊腹肌~呵呵哈哈哈,發出神經質的笑聲!呵呵哈哈哈")
        self.pros=Array.init(repeating: p, count: 7)

        self.initViews()


    }

    //初始化檢視
    func initViews() {

        //建立流式佈局
        let layout=UICollectionViewFlowLayout()

        //設定單元格屬性
        //設定單元格大小
        layout.itemSize=CGSize.init(width: 150, height: 150)

        //設定單元格內邊距
        layout.sectionInset=UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
        //設定行間距
        layout.minimumLineSpacing=10
        //設定單元格間距
        layout.minimumInteritemSpacing=10

        self.coloction=UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)

        //設定單元格標示與單元格型別 
        //單元格標示是為了 複用單元格 防止每次都重新建立 跟 Android的holder 一個道理
        self.coloction.register(ProCollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
        self.coloction.backgroundColor=UIColor.white

        self.coloction.delegate=self
        self.coloction.dataSource=self

        self.view.addSubview(self.coloction)


    }

    let NUM_COLUM=2 //每行的單元格數
    //實現重要的資料來源協議
    //行數 節數
    func numberOfSections(in collectionView: UICollectionView) -> Int {

        //計算節數 即 行數
        if(self.pros.count%NUM_COLUM==0){

           return self.pros.count/NUM_COLUM
        }

        return self.pros.count/NUM_COLUM+1

    }

    //每一行的單元格數
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        //判斷是否源資料能否佔滿每一行 佔滿返回2個 不能佔滿 返回一個
        if((section+1)*NUM_COLUM<=self.pros.count){

            return NUM_COLUM

        }

        return 1


    }

    //為單元格提供資料
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as! ProCollectionViewCell

        let p:ProjectMy=self.pros[indexPath.section*NUM_COLUM+indexPath.row]

        cell.name.text=p.name
        cell.details.text=p.description

        return cell


    }


    //實現委託協議 實現兩個常用的
    //選中單元格之後觸發
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {



    }

    //取消選中單元格之後觸發
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {


    }



}

接下來學習IOS中最重要的控制元件,UITableView 最常用的 相信有這一節的基礎,UITableView 不會太難~