簡體   English   中英

在iOS Swift中單擊按鈕向UITableView添加項目

[英]add an item to UITableView on button click in iOS Swift

我是iOS開發的新手,並且正在使用教程來創建一個簡單的待辦事項列表應用程序

我有一個視圖控制器,向其中添加了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()
}

更改數據源后,您需要重新加載數據以將更改反映到UI。 為了更有效地重新加載和重新加載UITableView的一部分,請檢查UITableView的其他“重新加載”方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM