【问题标题】:How do I add values in dictionary?如何在字典中添加值?
【发布时间】:2017-03-19 19:16:06
【问题描述】:

我正在制作一个需要标题和笔记的 iOS 笔记应用。我的标题有textField,笔记有textView。然后我将这两个添加到一个数组中,并将它们附加到我的tableView 中,我们可以在其中看到标题和注释。我正在使用的代码将我的所有注释附加在tableView 中,并为所有标题显示相同的内容。我知道我必须为此使用dictionary,但我该如何实现呢?这是VC的代码,有textViewtextField

@IBAction func addItem(_ sender: Any)
{
        list.append(textField.text!)
        list2.append(notesField.text!)
}

其中listlist2 为空array 在我的tableView 中,我有可扩展的单元格,其中有一个textView 来显示list2 的内容,该VC 的代码是:

override func awakeFromNib() {
    super.awakeFromNib()

    textView.text = list2.joined(separator: "\n")

}

【问题讨论】:

  • 阅读 Swift 语言指南。

标签: ios swift uitableview nsmutabledictionary


【解决方案1】:

只需要一个字典数组

var arrOfDict = [[String :AnyObject]]()
var dictToSaveNotest = [String :AnyObject]()

@IBAction func addItem(_ sender: Any)
{
  dictToSaveNotest .updateValue(textField.text! as AnyObject, forKey: "title")
  dictToSaveNotest .updateValue(NotesField.text! as AnyObject, forKey: "notesField")
  arrOfDict.append(dictToSaveNotest)
}

只需在tableView数据源方法中填充它只需在tableViewCell中创建两个outlet类titleLable和notesLabel

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

        cell.titleLabel.text = arrayOfDict[indexPath.row]["title"] as! String!
        cell.notesLabel.text = arrayOfDict[indexPath.row]["notesField"] as! String!

        return cell
    }

注意:我没有在代码上测试过,但希望它一定能工作。 祝一切顺利 。

【讨论】:

    【解决方案2】:

    在 Swift 中通过赋值将元素添加到字典中:

    var dict = [String : String]()
    
    let title = "My first note"
    let body = "This is the body of the note"
    
    dict[title] = body // Assigning the body to the value of the key in the dictionary
    
    // Adding to the dictionary
    if dict[title] != nil {
        print("Ooops, this is not to good, since it would override the current value") 
    
        /* You might want to prefix the key with the date of the creation, to make 
        the key unique */
    
    } else {
    // Assign the value of the key to the body of the note
        dict[title] = body
    }
    

    然后您可以使用元组遍历字典:

    for (title, body) in dict {
        print("\(title): \(body)")
    }
    

    如果您只对正文或标题感兴趣,则可以通过将标题或正文替换为 _ 来简单地忽略另一个,如下所示:

    for (_, body) in dict {
        print("The body is: \(body)")
    }
    // and
    for (title, _) in dict {
        print("The title is: \(title)")
    }
    

    标题/正文也可以通过字典的键或值属性访问:

    for title in dict.keys {
        print("The title is: \(title)")
    }
    // and
    for body in dict.values {
        print("The body is: \(body)")
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2021-12-30
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多