将单元格添加到TableView

时间:2018-10-18 03:55:37

标签: swift xcode uitableview

我正在尝试创建一个简单的应用程序,可以在其中将类单元格添加到TableView中,但是当我单击“添加”按钮时它不会显示。我不确定我在哪部分做错了。

这是我的Main.storyboard

enter image description here

这是我在ManageViewController.swift中的代码

import UIKit

class ManageViewController : UIViewController, UITableViewDataSource{

@IBOutlet weak var tableView: UITableView!
var classList = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    //classList = ["CSC 2431","CSC 4498"]
    createAlert(title: "Add class", message: "Click plus button to add class")
    classList = ["CSC 2431","CSC 4898"]
    // Do any additional setup after loading the view.
}

@IBAction func onAddTapped(_ sender: UIBarButtonItem) {
    let alert = UIAlertController(title: "Add Class", message: nil, preferredStyle: .alert)
    alert.addTextField { (classListTF) in
        classListTF.placeholder = "Enter Class"
    }
    let action = UIAlertAction(title: "Add", style: .default) { (_) in
        guard let list = alert.textFields?.first?.text else { return }
        print(list)
        self.classList.append(list)
        self.tableView.reloadData()
    }
    alert.addAction(action)
    present(alert, animated: true)
}

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

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "classCell")
    cell.textLabel?.text = classList[indexPath.row]
    return(cell)
}

}

2 个答案:

答案 0 :(得分:1)

我认为您忘记在桌上设置dataSource。您可以在Interface Builder或viewDidLoad()中进行此操作。

tableView.dataSource = self

答案 1 :(得分:0)

在主线程上重新加载 tableview

DispatchQueue.main.async {
 // Perform your async code here
  Self.tableview.reloadData()
  }
相关问题