Swift語言IOS8開發戰記9.Data Model

來源:互聯網
上載者:User

標籤:ios8   swift   data model   資料   結構   

上一話中實現了兩個控制器間的傳值,最終效果


這是我們的首頁面:


在ViewController中我們首頁顯示的內容是放到不同的數組中的:

var restaurantNames = ["cg1","cg2","cg3","cg4","cg5","cg6","cg7","cg8","cg9","cg10","cg11"]    var restaurantImages =    ["128.png","129.png","130.png","131.png","132.png","133.png","134.png","135.png","136.png","137.png","138.png","139.png","140.png"]

今天我們想要把首頁面中的資訊進行整合,反映到跳轉頁面中,這就要應用到程式中的Model。通過觀察,我們每一行所展示的內容,格式上都是一樣的,有圖片有標題,現在我們把這個模型單獨分離出來。建立一個資料模型,也就是一個cocoa touch class,命名為Rest,代碼如下:

import UIKitclass Rest: NSObject {    var name: String = ""    var image: String = ""    var location: String = ""    var type: String = ""    var isVisit: Bool = false    init(name: String,image: String,location: String,type: String,isVisit: Bool){        self.name = name    self.image = image    self.location = location    self.type = type    self.isVisit = isVisit    }}
Rest就是我們資訊展示的結構,現在建立一個類DataArray,把初始化的資訊放到其中,代碼如下:

import UIKitclass DataArray: NSObject {    var tempArray = [Rest]() //臨時變數    var dataArray:[Rest] {        get {            return tempArray        }    }        override init(){        tempArray = [     Rest(name: "cg1", image: "128.png", location: "xd1", type: "Cafe", isVisit: false),     Rest(name: "cg2", image: "129.png", location: "xd2", type: "Cafe", isVisit: false),     Rest(name: "cg3", image: "130.png", location: "xd3", type: "Tea", isVisit: false),     Rest(name: "cg4", image: "131.png", location: "xd4", type: "Cafe", isVisit: false),     Rest(name: "cg5", image: "132.png", location: "xd5", type: "Tea", isVisit: false),     Rest(name: "cg6", image: "133.png", location: "xd6", type: "Cafe", isVisit: false),     Rest(name: "cg7", image: "134.png", location: "xd7", type: "Cafe", isVisit: false),     Rest(name: "cg8", image: "135.png", location: "xd8", type: "Cafe", isVisit: false),     Rest(name: "cg9", image: "136.png", location: "xd9", type: "Cafe", isVisit: false),     Rest(name: "cg10", image: "137.png", location: "xd10", type: "Cafe", isVisit: false),     Rest(name: "cg11", image: "138.png", location: "xd11", type: "Tea", isVisit: false),                    ]                    }    }

ViewController中的相關資訊就沒用了,我們可以刪除掉,修改後的ViewController代碼如下:

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {    var restArray = DataArray().dataArray    var tableView = UITableView()    override func viewDidLoad() {        super.viewDidLoad()        self.navigationItem.title = "cgGo"                tableView = UITableView(frame: CGRectMake(0, 0, 320, 568), style: UITableViewStyle.Plain)//定義一個tableview        self.view.addSubview(tableView)//不添加看不到        tableView.dataSource = self        tableView.delegate = self //之前是在storyboard中設定的,現在改為手動設定        tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "Cell")        // Do any additional setup after loading the view, typically from a nib.    }    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {      return restArray.count            }     func numberOfSectionsInTableView(tableView: UITableView) -> Int {        return 1;    }    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        let identiString = "Cell" //代碼複用        var cell = tableView.dequeueReusableCellWithIdentifier(identiString,forIndexPath : indexPath) as? CustomTableViewCell        if cell == nil {            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identiString) as? CustomTableViewCell        }        var rest = restArray[indexPath.row]        var restName = rest.name        var restLocation = rest.location        var imageName = rest.image        var restType = rest.type        cell?.initWith(imageName, restName: restName, restLocation: restLocation, restType: restType)        if rest.isVisit{            cell?.accessoryType = .Checkmark        } else {            cell?.accessoryType = .None        }        return cell!    }    override func prefersStatusBarHidden() -> Bool { //隱藏上側邊欄中的電量、訊號等資訊        return true    }            func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {            tableView.deselectRowAtIndexPath(indexPath, animated: true)            let callActionHandler = {(action:UIAlertAction!) -> Void in                let alertMessage = UIAlertController(title: "Service is unavalable", message: "You can choice another rest" , preferredStyle: UIAlertControllerStyle.Alert)                alertMessage.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil))                self.presentViewController(alertMessage, animated: true, completion: nil)            }        let option = UIAlertController(title: nil, message: "What are you goning to do?", preferredStyle: UIAlertControllerStyle.ActionSheet)            //callAction        let callAction = UIAlertAction(title: "Call"+"180-123-\(indexPath.row)", style: UIAlertActionStyle.Default, handler: callActionHandler)//自訂的callActionHandler來響應點擊的事件            //markAction            let markAction = UIAlertAction(title: "I'm here", style: UIAlertActionStyle.Default, handler: {                (action:UIAlertAction!) ->Void in                let cell = tableView.cellForRowAtIndexPath(indexPath)                cell?.accessoryType = UITableViewCellAccessoryType.Checkmark   //對號                self.restArray[indexPath.row].isVisit = true            })            option.addAction(markAction)                        //cancelAction        let cancelAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Cancel, handler: nil)       // self.presentViewController(option, animated: true, completion: nil)            let detail = DetailViewController()                        self.navigationController?.pushViewController(detail, animated: true)            var image = restArray[indexPath.row].image            detail.imageName = image        option.addAction(cancelAction)            option.addAction(callAction)    }    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {        return 80    }    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {        if editingStyle == .Delete {          self.restArray.removeAtIndex(indexPath.row)        }        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)    }    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {        let shareAction = UITableViewRowAction(style: .Default, title: "Share", handler: {            (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in            let menu = UIAlertController(title: "Share Action", message: nil, preferredStyle: .ActionSheet)            let csdnAction = UIAlertAction(title: "csdn", style: .Default, handler: nil)            menu.addAction(csdnAction)            let  cancelAction = UIAlertAction(title:"Cancel", style: .Cancel, handler: nil)            menu.addAction(cancelAction)            self.presentViewController(menu, animated: true, completion: nil)                               })            let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: {            (action: UITableViewRowAction!,indexPath: NSIndexPath!) -> Void in        })return [deleteAction, shareAction]    }    }


可以看到之前單個的數組被名為restArray的model取代了,在定義cel的代理方法中引用restArray執行個體,顯示效果


Swift語言IOS8開發戰記9.Data Model

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.