Swift之小项目实战

ViewController.swift

import UIKit

class ViewController: UITableViewController {

    
    //声明模型数组
    var persons: [Person]?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //获取网络数据
        loadData { (dataList) -> () in
            print(dataList)
            self.persons = dataList
            
            //刷新表格
            self.tableView.reloadData()
        }
    
    }
    
    //MARK: 模拟网络数据请求
    func loadData(finished: (dataList: [Person]) -> () ) {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            //开始网络请求耗时操作 
            
            
            //创建容器数组  初始化数组
            var array = [Person]()
            //字典转模型
            for i in 0..<50 {
                let name = "范冰冰\(i)"
                let age = random() % 20 + 10
                let p = Person(dict: ["name" : name, "age" : age])
                //添加对象 
                array.append(p)
            }
            
            //请求结束  在主线程回调
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                //执行闭包
                
                //回调模型数组
                finished(dataList: array)
            })
        }
    }

}

//MARK: tableViewDelegate & Datasource
extension ViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return persons?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //类型转换  会涉及到 ? !  具体的转换类型 可以根据Xcode智能提示
        //是根据接受的类型 到时可选还是必选 来确定 用 ? 还是 !
        let cell = tableView.dequeueReusableCellWithIdentifier("DemoCell", forIndexPath: indexPath) as! PersonCell
        //懒加载是无处不在的
        cell.person = persons![indexPath.row]
        return cell
    }
}

Person.swift

import UIKit

class Person: NSObject {
    var name: String?
    var age: Int = 0
    
    //构造函数 - KVC
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    //需要生写 description
    //只读属性
    override var description: String {
        let keys = ["name" , "age"]
        let dict = dictionaryWithValuesForKeys(keys)
        return dict.description
    }
}

PersonCell.swift

import UIKit

class PersonCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var ageLabel: UILabel!
    
    
    var person: Person? {
        didSet {
            nameLabel.text = person?.name
            //转译的过程中 字符串拼接  如果是可选类型  自动添加 optional
            ageLabel.text = "\(person?.age ?? 0)"
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


你可能感兴趣的:(Swift教程)