我正在为我的学校设计一个应用程序,我正在尝试使用 View Controller 中的 TableView 制作一个简单的目录。我开始尝试制作对象,但后来切换到一个更简单的数组,仍然没有任何运气。不知道是代码问题还是 Storyboard 问题。这是 View Controller 的代码:
import UIKit
class DirectoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var backButton2: UIButton!
@IBOutlet weak var directoryTableView: UITableView!
// @IBOutlet weak var nameLabel: NSLayoutConstraint!
// let searchController = UISearchController(searchResultsController: nil)
// var directoryObjects: NSMutableArray! = NSMutableArray()
var names = ["Teacher 1", "Teacher 2", "Teacher 3"]
override func viewDidLoad() {
super.viewDidLoad()
/*
self.directoryObjects.addObject("Teacher 1")
self.directoryObjects.addObject("Teacher 2")
self.directoryObjects.addObject("Teacher 3")
self.directoryTableView.reloadData()
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Mark - tableview
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let directoryCell = self.directoryTableView.dequeueReusableCellWithIdentifier("directoryCell", forIndexPath: indexPath) as! DirectoryTableViewCell
// directoryCell.directoryLabel.text = self.directoryObjects.objectAtIndex(indexPath.row) as? String
directoryCell.directoryLabel.text = names[indexPath.row]
return directoryCell
}
@IBAction func backButton2Tapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
这是 DirectoryTableViewCell 的代码:
import UIKit
class DirectoryTableViewCell: UITableViewCell {
@IBOutlet weak var directoryLabel: UILabel!
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
}
/*
func directoryTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
*/
}
最佳答案
您必须设置代表。最简单的方法是在代码中。
在viewDidLoad
中添加:
directoryTableView.delegate = self
directoryTableView.dataSource = self
这将允许调用那些 tableView
函数。
我还建议更改:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 3
}
到:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return names.count
}
关于ios - 使用数组的 TableView 不起作用-xcode 7.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617723/