数组索引超出tableView的范围

时间:2015-07-09 03:31:53

标签: ios arrays uitableview

您好朋友我正在尝试完成它在youtube上的应用程序。 Xcode中有些东西已经改变了。问题是如下:

我创建了两个类型为array的变量,并将它们初始化为viewDidLoad

var names:[String]?     var颜色:[UIColor]?

override func viewDidLoad() {
    super.viewDidLoad()
    names = Array()
    colors = Array()
}

然后我制作了一个segue来从视图中提取数据。这项工作正确,因为我通过控制台尝试尝试:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let identifier = segue.identifier
    if identifier == "CreateColor"
    {
        let createColorViewController = segue.destinationViewController as! CreateColorViewController
        createColorViewController.delegate = self

    }
}

这个函数带来一个字符串和一个颜色(我用这个尝试segue):

func createColor(name: String, color: UIColor) {
    names?.append(name)
    colors?.append(color)
}

然后这个功能:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return 1
}

然后是tableview的这个函数:

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

    if cell == nil
    {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellId")
    }
        cell?.backgroundColor = colors![indexPath.row]
        cell?.textLabel?.text = names![indexPath.row]

    return cell!
}

问题是在视频中这段代码运行良好。但对我来说,Xcode向我展示了“数组索引超出范围”。我尝试使用任何valor初始化两个数组并且应用程序运行正常,但是当我转到tableView它获取名称和颜色并返回到表时,它不会带来任何结果。

我真的想知道发生了什么:(

youtube上的视频是:

https://www.youtube.com/watch?v=C_jylonPa8k

感谢您的关注。

1 个答案:

答案 0 :(得分:2)

假设您colors& names具有相同数量的对象。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    // return 1
    // must be your dataSource count. 
    return colors.count
}