我正在构建一个待办事项列表应用程序。我正在尝试单击添加按钮添加待办事项。它打开一个带有输入标题的警报。我为添加的 Item 创建了一个类:
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”类是用来获取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
}
您正在尝试将类型错误的项目附加到 listCourse。由于您将 listCourse 定义为 myItems 实例的数组,因此您只能向它附加该类的实例。要修复它只需更改var listCourse : [myItems]?
为var listCourse = [ToDoItem]()
还要修复您的 UITableViewDataSource 方法:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "macell1", for: indexPath)
let item = listCourse[indexPath.item]
cell.textLabel.text = item.title
return cell
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句