【问题标题】:Swift: Array Size with UITableViewSwift:使用 UITableView 的数组大小
【发布时间】:2016-04-02 10:14:33
【问题描述】:

我试图弄清楚数组如何与 Swift 一起工作。我了解您使用let 创建一个不可变数组并使用var 创建一个可变数组。然而,Swift 的数组与 Objective 的 NSArrayNSMutableArray 并不完全相同。我明白了。

在下面的示例中,我创建了一个包含一个元素的可变数组。实际上,我想从没有元素开始。但如果我这样做,我将无法向其中添加新字符串。如果我从一个元素开始,那么在删除原始元素后我将无法向其添加新字符串。那我做错了什么?

谢谢

编辑

class ViewController: UIViewController {
    let textCellIdentifier = "TextCell"
    var myArray:[String] = ["GGG"] // or var myArray:[String] = []

    @IBAction func add1Tapped(sender:AnyObject) {
        let index = tableView1.indexPathForSelectedRow;
        let selectedRow = index()?.row
        if selectedRow < 0 {
            return
        } else {
            let txt = nameField1.text
            myArray.append(txt)
            tableView1.reloadData()
        }
    }

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

    func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:textCellIdentifier)
        let row = indexPath.row
        cell.textLabel!.text = myArray[row]
        return cell
    }
}

【问题讨论】:

  • "我想从没有元素开始。但如果这样做,我将无法向其中添加新字符串。"。为什么?
  • 您可以随时将元素添加到您的array,如下所示。 myArray.append("your string")
  • 它与 UITableview 有什么关系?
  • @Eendje 那是因为应用程序启动时在其数组中没有字符串开始。桌子是空的。
  • @Pyro 显然,table 指的是 myArray。

标签: ios arrays swift uitableview


【解决方案1】:

您的所有需求都应该按预期工作:

// create an empty array of strings
var myArray: [String] = []

// add two elements
myArray.append("the first element")
myArray.append("the second element")

// remove both elements
myArray.removeAll()

// add another element
myArray.append("the third but now first element")

myArray.count

编辑

尝试像这样更改您的添加方法:

@IBAction func add1Tapped(sender:AnyObject) {
    if let _ = tableView1.indexPathForSelectedRow, txt = nameField1.text {
        print("will append \(txt) to myArray")
        myArray.append(txt)
        tableView1.reloadData()
    }
}

【讨论】:

  • 谢谢,但不行。我已经说过“如果我这样做,我将无法为其添加新字符串。”
  • 这和你的“myArray.append("the first element")”和IBAction差不多。
  • 但必须有所不同。 :) 因为在我的情况下它有效。所以如果你需要一些帮助,我猜你必须显示一些代码......
  • 看看我的帖子底部,修改你的代码,看看打印语句是否被执行...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2012-06-09
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多