我无法使用swift编程语言在tableview中显示数组的元素。我做了一些研究,但无法解决问题。在下面,您可以从此处查看我的代码并将项目下载为.zip文件:http://1drv.ms/1Ca2hyp
我也可以提供一些视频。他们是11分10秒。总计很长
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var myTableView: UITableView!
var cars = [String]()
var newCar: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cars = ["BMW","Audi", "Volkswagen"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cars.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = cars[indexPath.row]
return cell
}
}
答案 0 :(得分:9)
您忘记将控制器注册为UITableView的数据源 将其添加到您的代码中:
@IBOutlet var myTableView: UITableView! {
didSet {
myTableView.dataSource = self
}
}
答案 1 :(得分:2)
也许您忘记将这两行添加到视图控制器的viewDidLoad
方法中:
yourTableView.delegate = self
yourTableView.dataSource = self
答案 2 :(得分:1)
class SelectCategoryViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var CategeryArray = ["Food","Travel","Lifestyle","Card","MyReserve","Game","Songs","Movies","Entertainment","Business","Education","Finance","Drink","Sports","Social","Shopping"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.dataSource = self
self.tableView.delegate = self
}
}
extension SelectCategoryViewController: UITableViewDelegate,UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CategeryArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
cell.textLabel?.text = self.CategeryArray[indexPath.row]
return cell
}
}
在Main.storyboard中设置标识符= TableViewCell 并设置 TableViewCell
的类名