在Swift中,将UITableView添加到UIViewController中遇到问题

8
所以我正在尝试构建一个单屏应用程序,其中我从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
}



}

用户完成输入后,您是否重新加载了您的表格视图? - gabbler
你需要将 UITextFieldDelegate 设置为 self,并在用户输入文本时重新加载表格。 - Suhit Patil
感谢您的帮助。现在的问题是,在self.tableView.reloadData()代码行中,我收到了一个错误提示:“(UITableView,numberOfRowsInSection:Int)-> Int'没有名为'reloadData'的成员”。 - CL8989
另外,对于UITextField的“addGroup”,我将其拖到了UIViewController上,并在storyboard中设置为代理。我也添加了你的代码行。再次感谢。 - CL8989
1
尝试使用 self.tableView!.reloadData() - gabbler
2个回答

22

首先,按照以下方式为您的表视图创建一个IBOutlet

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

var groupList = [String]()
@IBOutlet weak var addGroup: UITextField!
@IBOutlet weak var tableView: UITableView!  //<<-- TableView Outlet

// Rest of your code..

}

在你的viewDidLoad方法中执行以下操作:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "groupcell")

    self.addGroup.delegate = self
    tableView.delegate = self
    tableView.dataSource = self
}

在将元素添加到groupList后,您可以reload您的tableView。您可以使用以下代码:

```swift tableView.reloadData() ```
@IBAction func addGroupButton(sender: AnyObject) {

    // Your Code

    } else {

        groupList.append(addGroup.text)
        self.tableView.reloadData()

    }

   //Your Code

}

并更新这个函数:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("groupcell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel.text = self.groupList[indexPath.row]
    return cell
}

你可以在这里检查我为你创建的最终代码。


1
这非常有帮助。完全解决了我的问题,谢谢大家。 - CL8989
谢谢你们解决我的问题。 - Imran Sh
很高兴能为您效劳.. :) - Dharmesh Kheni
1
哇,我整个早上都被这个问题困扰着,这篇文章帮了我很大的忙。谢谢@DharmeshKheni。 - Matty

0
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    addGroup.delegate = self // You can do this in storyboard also
    addGroup.placeholder = "Enter Group Name"
}    

@IBAction func addGroupButton(sender: AnyObject) {

        self.view.endEditing(true)

        var error = ""

        if addGroup.text == "" {

            error = "Please enter a Group!"
        } else {

            groupList.append(addGroup.text)

           //reload the table after adding text to array
            self.tableView.reloadData();

        }

        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 = ""


    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接