在Swift中的UIViewController中添加UITableView的问题

时间:2022-06-08 07:48:24

So I'm attempting to build a single screen app where I start with a UIViewController. On top of that there is a UITextfield, a button, and a UITableView.

所以我试图建立一个单一的屏幕应用程序,我开始使用UIViewController。最重要的是,有一个UITextfield,一个按钮和一个UITableView。

Essentially the intended functionality of the app is for a user to type a word into the UITextField, hit a button, and have it show up on the UITableView.

本质上,应用程序的预期功能是让用户在UITextField中键入单词,点击按钮,并将其显示在UITableView上。

I never have problems doing this when the the button appends the UITextField entries to a UITableViewController on a different screen, but for some reason I'm having problems with a UITableView embedded on the UIViewController... On my storyboard I did link the UITableView as a delegate and datasource of the UIViewController so that shouldn't be the problem.

当按钮将UITextField条目附加到不同屏幕上的UITableViewController时,我从来没有遇到过这样的问题,但由于某种原因我在UIViewController上嵌入了UITableView时出现问题...在我的故事板上,我确实将UITableView链接为UIViewController的委托和数据源,这应该不是问题。

Any ideas? My code is posted below.

有任何想法吗?我的代码发布在下面。

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
}



}

2 个解决方案

#1


21  

First of all create an IBOutlet for your table view this way :

首先以这种方式为表视图创建一个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..

}

After that do this in your viewDidLoad method:

之后在viewDidLoad方法中执行此操作:

override func viewDidLoad() {
    super.viewDidLoad()

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

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

After that you can reload your tableView once the element is added into groupList. Here you can do this:

之后,您可以在将元素添加到groupList后重新加载tableView。在这里你可以这样做:

@IBAction func addGroupButton(sender: AnyObject) {

    // Your Code

    } else {

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

    }

   //Your Code

}

And Update this function:

并更新此功能:

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
}

And you can check final code which I created for you is HERE.

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

#2


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


    }

#1


21  

First of all create an IBOutlet for your table view this way :

首先以这种方式为表视图创建一个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..

}

After that do this in your viewDidLoad method:

之后在viewDidLoad方法中执行此操作:

override func viewDidLoad() {
    super.viewDidLoad()

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

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

After that you can reload your tableView once the element is added into groupList. Here you can do this:

之后,您可以在将元素添加到groupList后重新加载tableView。在这里你可以这样做:

@IBAction func addGroupButton(sender: AnyObject) {

    // Your Code

    } else {

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

    }

   //Your Code

}

And Update this function:

并更新此功能:

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
}

And you can check final code which I created for you is HERE.

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

#2


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


    }