我正在構建待辦事項列表應用程序。我正在嘗試添加點擊添加按鈕的待辦事項。它會打開一個裏面有輸入標題的提醒。我做了一個類的附加項目:Swift 3使用uialertcontroller向uitableviewcontroller添加新行
class ToDoItem
{
var title: String
public init(title: String)
{
self.title = title
}
}
這裏是我的代碼中添加一個新行:
func didTapAddItemButton(_ sender: UIBarButtonItem)
{
let alert = UIAlertController(
title: "New to-do item",
message: "Insert the title of the new to-do item:",
preferredStyle: .alert)
alert.addTextField(configurationHandler: nil)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
if let title = alert.textFields?[0].text
{
self.addNewToDoItem(title: title)
}
}))
self.present(alert, animated: true, completion: nil)
}
private func addNewToDoItem(title: String)
{
let newIndex = listCourse?.count
listCourse?.append(ToDoItem(title: title))
tableView.insertRows(at: [IndexPath(row: newIndex!, section: 0)], with: .top)
}
但我得到這個錯誤:
Cannot convert value of type "ToDoItem" to expected argument type "myItems"
這裏是myItems類:
class myItems {
var title: String?
var content: String?
var date: String?
var author: String?
init(title: String, content: String, date: String, author: String){
self.title = title
self.content = content
self.date = date
self.author = author
}
func mapping(map: Map) {
title <- map["title"]
content <- map["description"]
date <- map["pubDate"]
author <- map["author"]
}
}
這個「myItems」cl屁股是用來獲取json數據的,後來我會從數據庫中獲取數據。
最後一件事:
var listCourse : [myItems]?
listCourse是tableViewController顯示單元的列表。
我不明白的錯誤,我只是想添加在列表中輸入標題
[編輯]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
return cell
}
錯誤說,你不能輸人'ToDoItem'的對象添加到類型myItems'的'對象的數組。爲什麼'ToDoItem'甚至存在?你可能應該只是使用'myItems'類並刪除'ToDoItem'。 (順便說一下,'myItems'對於一個類來說是一個可怕的名字,它聽起來像是一個myItem對象的數組,但是它真的是一個類,非常令人困惑。我認爲ToDoItem是一個非常好的名字。 ) – paulvs
我之前做了myItems而不是ToDoItem,它也給我一個錯誤: 缺少參數內容,日期,作者 但我只是想添加標題,我不明白爲什麼我不能只使用標題。 我要改變名字! thx諮詢! –
這很簡單,只需改變你的'init'方法,以便不需要所有參數,只需要'title'參數。 – paulvs