我下面的代码只是基本的表格视图,里面什么都没有。使用文本字段和按钮。用于放置文本的文本字段和用于提交文本的按钮。我希望用户只能在数组中输入 int。如何使用文本字段和按钮向此空白表视图添加多个条目?
import UIKit
var list = [""]
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet var placeText: UITextField!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(list.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
return(cell)
}
@IBAction func enterText(_ sender: Any) {
}}
将UITextfield
中的文本添加到列表中,然后重新加载表视图:
@IBAction func enterText(_ sender: Any) {
let newText = textfield.text
list.append(newText)
tableView.reloadData()
}
Swift 3.0
@IBAction func enterText(_ sender: Any) {
if !placeText.text!.isEmpty {
list.append(placeText.text)
tableview.reloadData()
}
}