从数组中的 TableViewController 中显示列表,数组中只有 1 个项目

Displaying List in TableViewController from array with only 1 item in array

学习编码 Swift,我试图将一个数组添加到 TableView 控制器,这样数组中的每个项目在 table 中都是它自己的行,一切顺利,但是如果我数组中只有一项,它不显示。

var myArray = [[""]]
var count = myArray.count
var myArray2 = [""]

for index in 0...count-1 {
    myArray2.append(myArray[index][0])
}

在稍后的函数中,我将 myArray2 添加到列表中,但正如我所说,如果列表中只有 1 个项目,它就不起作用。认为这是因为我正在做 0...count-1,所以 0...0,但无法找到另一种方法。

谢谢

完整代码:

import UIKit

struct MyVariables {
static var myArray = [[""]]
}

class HistoryViewController: UIViewController, UITableViewDelegate {
var myArray2 = [""]

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
println(MyVariables.myArray)
super.viewDidLoad()

var firstItem = MyVariables.myArray[0][0]
if firstItem == "" {
    MyVariables.myArray.removeAtIndex(0)
}

println(MyVariables.myArray.count)

var count = MyVariables.myArray.count
println(count)
var countIsNotZero = false
println(countIsNotZero)

myArray2.removeAll(keepCapacity: false)

if count != 0 {
    countIsNotZero = true
}
println(countIsNotZero)

if count != 0 {
    for index in 0...count-1 {
        myArray2.append(MyVariables.myArray[index][0])
        println(index)
    }
}
self.tableView.reloadData()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(myArray2.count)
return myArray2.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

println(myArray2.count)
if myArray2.count > 1{
    cell.textLabel?.text = myArray2[indexPath.row]
    println(myArray2.count)
} else {
    cell.textLabel?.text = ""
}
return cell
} 
}

您的 table 没有显示单个值,因为当数组没有至少两个项目时,您正在用空字符串填充标签的文本。如果您删除该支票,您的 table 将使用一项:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    println(myArray2.count)
    cell.textLabel?.text = myArray2[indexPath.row]
    return cell
}