我一直在尝试使用 xcode 6 和 ios8 使用 swift 创建一个表格 View ,但我在模拟器上没有得到任何东西,只是显示空(白色)。
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var myArr = ["one","two","three","four","five"]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = self.myArr[indexPath.row]
return cell;
}
}
我什至尝试过拖动一些元素,如按钮、开关等,但我在模拟器上没有得到任何东西。如果我下载并运行任何代码,它就可以工作。
最佳答案
这是我的工作代码,我不明白前一个代码出了什么问题,但我创建了一个新项目,然后它就工作了。 我只是将 TableView 拖到 View Controller 并分配委托(delegate)和数据源 然后来到viewcontroller.swift并尝试
import UIKit
class ViewController: UIViewController {
var items = ["a","b","c"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
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 numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myCell") as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
}
关于ios - 使用 swift 创建 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26341536/