【发布时间】:2014-12-09 06:18:19
【问题描述】:
所以我正在尝试构建一个单屏应用程序,从 UIViewController 开始。除此之外,还有一个 UITextfield、一个按钮和一个 UITableView。
本质上,应用程序的预期功能是让用户在 UITextField 中键入一个单词,点击一个按钮,然后让它显示在 UITableView 上。
当按钮将 UITextField 条目附加到不同屏幕上的 UITableViewController 时,我从来没有遇到过问题,但由于某种原因,我遇到了嵌入在 UIViewController 上的 UITableView 的问题......在我的故事板上我做了链接UITableView 作为 UIViewController 的委托和数据源,所以这不应该是问题。
有什么想法吗?我的代码贴在下面。
import UIKit
var groupList:[String] = []
class ExistingGroups: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource
{
@IBOutlet weak var addGroup: UITextField!
@IBAction func addGroupButton(sender: AnyObject) {
self.view.endEditing(true)
var error = ""
if addGroup.text == "" {
error = "Please enter a Group!"
} else {
groupList.append(addGroup.text)
}
if error != "" {
var alert = UIAlertController(title:"Error In Form", message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion:nil)
}))
self.presentViewController(alert, animated:true, completion:nil)
}
addGroup.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addGroup.placeholder = "Enter Group Name"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches:NSSet, withEvent event:UIEvent)
{
super.touchesBegan(touches, withEvent: event)
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
return true;
}
func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int {
return groupList.count
}
func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("groupcell") as UITableViewCell
cell.textLabel?.text = groupList[indexPath.row]
return cell
}
}
【问题讨论】:
-
用户完成输入后你是否重新加载了你的tableview?
-
您需要将 UITextFieldDelegate 设置为 self 并在用户输入文本时重新加载表格
-
感谢您的帮助。现在的问题是 self.tableView.reloadData();代码行,我收到一个错误“(UITableView,numberOfRowsInSection:Int)-> Int'没有名为'reloadData'的成员”
-
对于 UITextField “addGroup”,我确实将其拖到 UIViewController 并设置为情节提要上的委托。我还添加了您的代码行。再次感谢。
-
尝试使用
self.tableView!.reloadData()
标签: ios uitableview swift uiviewcontroller