我正在学习Swift,而且我曾经在Objective C中做过模式,但是我不明白如何在这里做。 我有使用TableView的UIViewController。当我将数组放入其中时,我工作正常。但根据MVC我想将数据移动到另一个类。我不知道该怎么做。我试过的一切都行不通。 谢谢!
我的代码,如何将tableDS移到外面:
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
//temp table data
let tableDS = ["fdf", "dfd"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableDS.count
}
let textCellIdentifier = "TableViewCell"
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyCell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as MyCell
let row = indexPath.row
cell.dayLabel.text = tableDS[row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
println(tableDS[row])
}
}
答案 0 :(得分:0)
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = tableDS[indexPath.row]
return cell
}
这应该有效。 如果要使用MVC模式,请创建一个新的单例类,在那里创建数组,然后创建一个返回数组的方法。
答案 1 :(得分:0)
首先,您需要使用空数组初始化表视图。当您从下面的代码示例中的另一个视图控制器加载MyViewController时,您可以传递数据,并将let tableDS = [“fdf”, “dfd”]
更改为var tableDS = [“fdf”, "dfd"]
。 let用于常量变量。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YourMyViewControllerSequeId" {
let myViewController = segue.destinationViewController as MyViewController
var myArrayToPass = ["learn swift", "or get a life"];
myViewController.tableDS = myArrayToPass
myViewController.tableView.reloadData()
}
}
答案 2 :(得分:0)
在表视图的MVC设计模式中,表视图是视图对象。控制器是视图控制器。
该模型是您用于存储数据的任何内容。
控制器对象充当模型和视图之间的中介。
对于简单的表视图,模型对象可以像数组一样简单。数组 模型。因此,没有理由将数据存储在单独的对象中。
如果您真的想让模型成为完全不同的对象,请创建一个新类。称之为MyTableViewModel。使MyTableViewModel类包含数据数组。还要使MyTableViewModel符合UITableViewDatasource协议。为此,您必须实现多种方法 - 特别是cellForRowAtIndexPath。
现在在视图控制器中,创建一个MyTableViewModel对象作为视图控制器的强属性,在其中安装数组,并使其成为表视图的数据源。
完成。
但是,再一次,将一个简单的数组视为模型是很常见的,让视图控制器通过在视图控制器中实现cellForRowAtIndexPath来提供单元格。