优化tableView加载cell与model的过程

优化tableView加载cell与model的过程

 

效果图

 

说明

1. 用多态的特性来优化tableView加载cell与model的过程

2. swift写起来果然要比Objective-C简洁了不少

 

源码

https://github.com/YouXianMing/Swift-TableViewDemo

https://github.com/YouXianMing/OC-TableViewDemo

//
//  ViewController.swift
//  Swift-TableViewDemo
//
//  Created by YouXianMing on 15/9/28.
//  Copyright © 2015年 YouXianMing. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let typeOneCellFlag : String! = "typeOneCellFlag"
    let typeTwoCellFlag : String! = "typeTwoCellFlag"
    
    var datasArray : NSMutableArray!
    var tableView  : UITableView!
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.initDatasArray()
        
        self.initTableView()
    }

    // 数据源相关
    func initDatasArray() {
    
        datasArray = NSMutableArray()
        datasArray.addObject(TypeOneModel(flag: typeOneCellFlag, cellHeight: 100, data: "TypeOneModel"))
        datasArray.addObject(TypeTwoModel(flag: typeTwoCellFlag, cellHeight: 200, data: "TypeTwoModel"))
    }
    
    // tableView相关
    func initTableView() {
    
        tableView = UITableView(frame: view.bounds, style: .Plain)
        tableView.delegate       = self
        tableView.dataSource     = self
        tableView.separatorStyle = .None
        view.addSubview(tableView)
        
        tableView.registerClass(TypeOneCell.classForCoder(), forCellReuseIdentifier: typeOneCellFlag)
        tableView.registerClass(TypeTwoCell.classForCoder(), forCellReuseIdentifier: typeTwoCellFlag)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        return datasArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        let model : BaseModel! = datasArray[indexPath.row] as! BaseModel
        
        let cell : BaseTableViewCell! = tableView.dequeueReusableCellWithIdentifier(model.cellFlag!) as! BaseTableViewCell
        cell.tableView                = tableView
        cell.indexPath                = indexPath
        cell.data                     = model.data
        cell.loadData()
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let model : BaseModel! = datasArray[indexPath.row] as! BaseModel
        
        return model.cellHeight!
    }
}

 

细节

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值