【发布时间】:2015-12-11 13:24:19
【问题描述】:
我开始开发this question 应用程序。 我从 tableView 的类别开始:
对于数据交换,我决定使用一个协议:
protocol Category {
func data(object:AnyObject)
}
在第一个ViewController中有如下代码:
class ViewController: UIViewController {
var items:[String] = ["Desktop","Tablet","Phone"]
let CategoriesData:Category? = nil
override func viewDidLoad() {
super.viewDidLoad()
CategoriesData?.data(items)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在第二个ViewController(Container中的tableView)中有如下代码:
class CategoriesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, Category {
@IBOutlet var table: UITableView!
var items:[String] = []
func data(object: AnyObject) {
self.items = (object as? [String])!
print(object)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = self.table.dequeueReusableCellWithIdentifier("SegueStage") as! TableViewCell
cell.nameLabel.text = items[indexPath.row]
return cell
}
}
对我来说,显然没关系。但是模拟器上什么也没出现。
我的问题是:如果Container用来呈现另一个viewController作为通过协议传递数据应该这样做?
【问题讨论】:
-
你从
CategoriesData开始为 nil。那是怎么改变的? (使用协议很好,但您仍然需要对实现协议的对象的引用。)
标签: swift uiviewcontroller swift2 swift2.1 swift-protocols