如果說MVC是最好的設計模式, 可能很多人并不贊同, 但是如果說MVC是最主流, 應用面最廣的設計模式, 我想這是毫無争議的. 不說廢話, 直接示範在Swift中如何使用MVC建立工程(我并沒有建立檔案夾, 大家按照自己實際需求來).
1, 建立檔案, 不多廢話.
2, ViewController中代碼
1 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
2
3 var tableView : UITableView!
4 var dataArray = [Model]()
5
6 override func loadView() {
7
8 super.loadView()
9 //循環生成字典
10 for var i = 0; i < 5; ++i{
11 let item: Dictionary = ["name" : "wang", "age" : "\(i)"]
12 let model = Model()
13 model.setValuesForKeysWithDictionary(item)
14 dataArray.append(model)
15 }
16
17 //初始化tableView
18 tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), style: UITableViewStyle.Plain)
19 tableView.delegate = self
20 tableView.dataSource = self
21
22 self.view.addSubview(tableView)
23
24 }
25 //tableView協定方法
26 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
27
28 let indentifier = "tableView"
29 var cell: MyTableViewCell!
30 cell = tableView.dequeueReusableCellWithIdentifier(indentifier) as? MyTableViewCell
31 if cell == nil{
32 cell = MyTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: indentifier)
33 }
34 cell.model = dataArray[indexPath.row]
35
36 return cell
37 }
38
39 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
40
41 return dataArray.count
42
43 }
44 override func viewDidLoad() {
45 super.viewDidLoad()
46 // Do any additional setup after loading the view, typically from a nib.
47 self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
48
49 }
50
51 override func didReceiveMemoryWarning() {
52 super.didReceiveMemoryWarning()
53 // Dispose of any resources that can be recreated.
54 }
3, Model中代碼
1 import UIKit
2
3 class Model: NSObject {
4
5 var name: String!
6 var age: Int = 0
7
8 }
4, MyTableViewCell中代碼
1 import UIKit
2
3 class MyTableViewCell: UITableViewCell {
4
5
6 var model: Model{
7 set{
8 nameLabel.text = newValue.name
9 ageLabel.text = String(stringInterpolationSegment: newValue.age)
10 }
11 get{
12 return self.model
13 }
14 }
15 var nameLabel: UILabel!
16 var ageLabel: UILabel!
17
18 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
19 super.init(style: style, reuseIdentifier: reuseIdentifier)
20 createCell()
21 }
22
23 required init?(coder aDecoder: NSCoder) {
24 fatalError("init(coder:) has not been implemented")
25 }
26
27 func createCell(){
28 nameLabel = UILabel()
29 ageLabel = UILabel()
30
31 self.contentView.addSubview(nameLabel)
32 self.contentView.addSubview(ageLabel)
33 }
34
35 override func layoutSubviews() {
36 super.layoutSubviews()
37 nameLabel.frame = CGRect(x: 0, y: 0, width: 50, height: 20)
38 ageLabel.frame = CGRect(x: 50, y: 0, width: 20, height: 20)
39 }
40
41
42
43 override func awakeFromNib() {
44 super.awakeFromNib()
45 // Initialization code
46 }