我需要在TableView中设置部分。每个部分都有不同的值类型,请参阅我的代码。但它不起作用。请告知正确的方法来设置值。请参阅屏幕截图以获取错误消息。注意:我在var detailsInSection的末尾删除了“)”,因为它无法正确显示。
var sectionTitles = ["WebSite", "Date Saved", "Document Used","Add Notes"]
var detailsInSection = [([String], [NSDate],[AnyObject],[String])]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailsInSection[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell")
cell?.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]
return cell!
}
答案 0 :(得分:0)
var detailsInSection = [([String], [NSDate],[AnyObject],[String])]
以上是一个元组数组。我从你的代码的其余部分猜测你想要一个数组数组。
var detailsInSection = [[String](), [NSDate](), [AnyObject](), [String]()]
你的数组将有4个元素,每个元素都是一个数组。
如果要处理不同的类型,请使用switch语句。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell")!
switch indexPath.section {
case 0:
cell.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]
case 1:
let date = detailsInSection[indexPath.section][indexPath.row]
// Do some date formatting etc
cell.textLabel!.text = PUT YOUR FORMATTED DATE HERE
case 2:
// Do any type casting etc.
let object = detailsInSection[indexPath.section][indexPath.row]
// Convert object to whatever is needed in text format.
cell.textLabel!.text = PUT YOUR OUTPUT HERE
case 3:
// This is a string so just assign it.
cell.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]
default:
// What to do here? Should never happen.
}
return cell
}
答案 1 :(得分:0)
不是存储由(String,NSDate,AnyObject,String)组成的元组,而是为每个部分存储一个数组。这将为您提供更多灵活性和更轻松的访问。将您的代码更改为:
var detailsInSection = [[AnyObject]]() // Note the type is 'AnyObject', so you can still store your strings, dates etc. here
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailsInSection[indexPath.section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell")!
cell.textLabel!.text = detailsInSection[indexPath.section][indexPath.row].description // Description will transfer your object to a string. If you want to change this behavior, you must process your objects according to their type.
return cell
}