2017-03-19 72 views
-1

我正在做一个需要标题和笔记的iOS笔记记录应用程序。我的笔记有textField,我的笔记有textView。然后,我将这两个数组添加到数组中,并将它们追加到我的tableView中,在那里我们可以看到标题和笔记。我正在使用的代码在tableView之后附加了我的所有笔记,并对所有标题显示相同。我知道我必须使用dictionary,但我该如何实现呢?这是有textViewtextField的VC代码如何在字典中添加值?

@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") 

} 
+1

阅读Swift语言指南。 – Alexander

回答

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类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 
    } 

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

0

您可以通过分配的元素添加到斯威夫特的字典:

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)") 
}