gpt4 book ai didi

ios - 在 iOS Swift 中单击按钮时向 UITableView 添加一个项目

转载 作者:行者123 更新时间:2023-11-29 02:07:58 25 4
gpt4 key购买 nike

我是 iOS 开发的新手,我正在使用 this教程,创建一个简单的 TO-DO 列表应用程序

我有一个 View Controller ,我在其中添加了一个 UITableView 和一个 UIBarButtonItem。我想在 UIBarButtonItem 单击时向 UITableView 添加一个项目(标题)。我写了代码,但我不确定哪里出了问题

class contactsMenu: UIViewController, UITableViewDataSource , UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

var toDoItems = [todoItem]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
if toDoItems.count > 0 {
return
}
}

override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}



@IBAction func addAGroupBtnclicked(sender: UIBarButtonItem) {
toDoItems.append(todoItem(text: "ok"))
}

@IBAction func backBtn(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toDoItems.count
}

func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell",
forIndexPath: indexPath) as UITableViewCell
let item = toDoItems[indexPath.row]
cell.textLabel?.text = item.text
return cell
}
}

和我的 todoItem.swift 文件:

class todoItem : NSObject{

var text: String

// A Boolean value that determines the completed state of this item.
var completed: Bool

// Returns a ToDoItem initialized with the given text and default completed value.
init(text: String) {
self.text = text
self.completed = false
}
}

最佳答案

假设 addAGroupBtnclicked() 是按钮的点击处理程序,用于添加新任务。

@IBAction func addAGroupBtnclicked(sender: UIBarButtonItem) {
toDoItems.append(todoItem(text: "ok"))
tableView.reloadData()
}

更改数据源后,您需要重新加载数据以将更改反射(reflect)到 UI 上。为了更有效地重新加载和重新加载 UITableView 的一部分,请检查 UITableView 的其他“重新加载”方法。

关于ios - 在 iOS Swift 中单击按钮时向 UITableView 添加一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29586932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com