【发布时间】:2017-07-05 22:08:01
【问题描述】:
我正在构建一个待办事项列表应用程序。我正在尝试单击添加按钮添加待办事项。它会打开一个带有输入标题的警报。我为添加的项目做了一个类:
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
}
【问题讨论】:
-
错误提示您无法将
ToDoItem类型的对象添加到myItems类型的对象数组中。为什么ToDoItem甚至存在?您可能应该只使用myItems类并删除ToDoItem。 (顺便说一句,myItems是一个类的可怕名称,它听起来像myItem对象的数组,但实际上是一个类,非常令人困惑。ToDoItem是一个非常好的类名称,我认为。 ) -
我之前用 myItems 而不是 ToDoItem 做的,它也给了我一个错误:缺少参数内容,日期,作者但我只想添加标题,我不明白为什么我不能只需使用标题。那我要改名字了!谢谢你的建议!
-
这很简单,只需更改您的
init方法,以便不需要所有参数,只需title参数。
标签: swift uitableview uialertcontroller