UITextField and UITableView on a single view controller - ios

I'm trying to make a view controller that has one text field that populates the tableview below, ideally the user will be able to continue to add to the tableview without jumping between two views.
I previously had it working with the text field on one view that populates a UITableView and used prepareForSegue to push the data to the table, but I haven't been able to get it to work with just one view.
Can anyone please point out where I'm going wrong or push me to a tutorial / documentation to help?
Edit: Clarity
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet var tableView: UITableView!
#IBOutlet weak var textField: UITextField!
var items: [String] = ["Pls", "work", "pls", "work", "pls"]
var foodGroup: FoodGroup = FoodGroup(itemName:"")
//var foodGroup: [FoodGroup] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Selected cell #\(indexPath)")
}
func addFood(sender: AnyObject!) {
if (countElements(self.textField.text) > 0) {
self.foodGroup = FoodGroup(itemName: self.textField.text)
}
}
#IBAction func addFoodToList() {
let source = FoodGroup
let foodGroup:FoodGroup = source.foodGroup
if foodGroup.itemName != "" {
self.foodGroup.append(foodGroup)
self.tableView.reloadData()
}
}
}

It seems like your intention here is to have your dataSource be an array of FoodGroup objects. If this is indeed the case you can get rid of your foodGroup instance variable and update your items definition to be like so:
var items = [FoodGroup]()
then in addFoodToList:
if self.textField.text != "" {
let foodGroup = FoodGroup(itemName: self.textField.text)
self.items.append(foodGroup)
self.tableView.reloadData()
}
and finally in cellForRowAtIndexPath:
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let foodGroup = self.items[indexPath.row] as FoodGroup
cell.textLabel.text = foodGroup.itemName
return cell
Also I don't quite see the intention of your the addFood(sender: AnyObject!) function. Looks like cruft. I would get rid of it. Good luck!

Related

Custom Cells Returning Blank in TableView Swift 3

So I am currently trying to populate a tableview with custom cells based on an API call. After I get the data to populate with, I reload the tableview. It has the data based on how many cells it has, but each one is blank. I've looked over some similar problems people had, but can't seem to find the fix. Any help would be great, thank you!
I call my API and collect the data I need. Then I reload the tableview.
class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
#IBOutlet var typeSwitch: UISegmentedControl!
#IBOutlet var searchBar: UITextField!
var timeoutTracker = 0
var items: [String] = []
var count = 1
func searchCall() {
Alamofire.request("http://www.plex.dev/api/search/" + type + "/" + searchBar.text!).responseJSON { response in
debugPrint(response)
if response.response == nil {
self.timeoutTracker = self.timeoutTracker + 1
if self.timeoutTracker == 5 {
self.timeoutTracker = 0
self.popUp()
}
else {
sleep(2)
self.searchCall()
}
}
if let json = response.result.value {
let jsonTest = JSON(json)
for x in jsonTest["results"] {
if let title = x.1["title"].string {
self.items.append(title)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.reloadData()
}
}
}
}
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return self.items.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! MovieCell
cell.movieTitle?.text = self.items[indexPath.row]
cell.moviePoster?.image = #imageLiteral(resourceName: "avatar.png")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
Here is the custom Cell Class
import UIKit
class MovieCell: UITableViewCell {
#IBOutlet var moviePoster: UIImageView!
#IBOutlet var movieTitle: UILabel!
#IBAction func addMovie(_ sender: AnyObject) {
}
}
Here is my storyboard:
And here is my blank tableview:
I hope it isn't something obvious, but thanks for the help either way!
EDIT: changing my identifier to something other than "cell" seemed to do the trick
Are you calling the searchCall() anywhere?
Also would suggest you to declare
tableView.delegate = self
tableView.dataSource = self
in viewDidLoad() of the SearchViewController and add the delegates and datasource of the UITableView as an extension to SearchViewController (it is a better code practice)
EDIT: After looking again at your cellForRowAt: try and replace your code with the following
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MovieCell
and not use self.tableView here
EDIT 2: Sometimes using the default cell identifier 'cell' can cause some problems, so better to use a different one such as 'movieCell'
I suspect you are registering a class or nib with your table view, but when you use prototype cells you should not do this. Also, you should use the more modern dequeueReusableCell(withIdentifier: String , for indexPath: IndexPath). Also, I would resist the temptation to ever call sleep.
Did you give the class to the cell and connect the outlets in cell

I have set value for cell of UITableView but why it didn't display?

I have created a UITableView and a UITableVIewCell in Main.storyboard and set it's dataSource and delegate to ViewController .Why UITableView didn't display texts when I run the code.
Another question is that does UITableView load before ViewLoad? If not why in func didRecieveResults() the Array of tableData can achieve datas but in func tableView() it was nil
The whole codes as following
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,HttpProtocol {
#IBOutlet weak var tv: UITableView!
#IBOutlet weak var iv: UIImageView!
#IBOutlet weak var playTime: UILabel!
#IBOutlet weak var progressView: UIProgressView!
var eHttp:HttpController = HttpController()
var tableData:NSArray = NSArray()
var channelData:NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
eHttp.delegate = self
eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
println("tableData.count:\(channelData)")
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!{
let cell = UITableViewCell(style:UITableViewCellStyle.Subtitle,reuseIdentifier:"douban")
let rowData:NSDictionary = self.tableData[indexPath.row] as! NSDictionary
cell.textLabel!.text = "hehehehe"//rowData["title"] as! String
cell.detailTextLabel!.text = "adasdasda"//rowData["artist"] as! String
return cell
}
func didRecieveResults(results:NSDictionary){
if (results["song"] != nil){
self.tableData = results["song"] as! NSArray
println(tableData)
}else if (results["channels"] != nil){
self.channelData = results["channels"] as! NSArray
// println(channelData)
}
}
}
As Lukas points out, you need to return the UITableViewCell at the end of the method.
In fact, what you posted shouldn't even compile, so I'm wondering if you posted your sample code incorrectly.
The first thing to try, and actually return the cell, update your code to:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
{
let cell = UITableViewCell(style:UITableViewCellStyle.Subtitle,reuseIdentifier:"douban")
let rowData:NSDictionary = self.tableData[indexPath.row] as! NSDictionary
cell.textLabel!.text = "hehehehe"//rowData["title"] as! String
cell.detailTextLabel!.text = "adasdasda"//rowData["artist"] as! String
// YOU ARE MISSING THIS LINE
return cell
}
Also ensure that you UITableViewDatasource is set properly, and that the required methods are functioning. Specifically, both numberOfRowsInSection and numberOfSectionsInTableView need to be returning values greater than 0. (In the code you posted, you are missing numberOfSectionsInTableView)
As Lukas said in a comment, you should make sure you return a value from your cellForRowAtIndexPath method otherwise it will refuse to build. If you've done that and you still don't see any cells, it's probably because either numberOfRowsInSection or numberOfSectionsInTableView are returning 0, so you should make sure they return a positive integer.

No call to my didSelectRowAtIndexPath function

I'm trying to create an app that displays some data on labels on the top of a screen, and then the lower half or so is a table which will allow selection of an item in the table to pop up another segue for editing a value. I'm struggling though to get the didSelectRowAtIndexPath to be called when an item on the list is selected by the user. I've put the code for the View controller below.
I've searched quite a bit and haven't found anything so far that explains the issue I'm seeing.
I think I've connected everything up correctly as far as delegates and datasource, and I'm not using any gesture captures so it's not those. Does anyone have any ideas?
I've attached screen grabs of the view controller connections and attributes inspector settings as well.
Connections screengrab
Attributes screengrab
import UIKit
class TemperatureViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var CurrentTemp: UILabel!
#IBOutlet weak var HeaterStatus: UILabel!
#IBOutlet weak var ChillerStatus: UILabel!
#IBOutlet weak var TempTableView: UITableView!
var settings = [TemperatureSettings] ()
var HeaterTemp:Float = 0.0
var ChillerTemp:Float = 0.0
var ThresholdTemp:Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.loadTempSettings()
TempTableView.delegate = self
TempTableView.dataSource = self
TempTableView.allowsSelection = true
TempTableView.editing = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.loadTempSettings()
}
func loadTempSettings() {
let TempSetting1 = TemperatureSettings(name: "Heater On at", CurrentSetting: HeaterTemp)!
let TempSetting2 = TemperatureSettings(name: "Chiller On at", CurrentSetting: ChillerTemp)!
let TempSetting3 = TemperatureSettings(name: "Threshold", CurrentSetting: ThresholdTemp)!
settings = [TempSetting1, TempSetting2, TempSetting3]
TempTableView.reloadData()
//refreshControl?.endRefreshing()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Stop spoof separators after the table entries for blank entries
tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
// Turn off the separator for each cell.
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
let cellIdentifier = "TemperatureSettingsTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TemperatureSettingsTableViewCell
let setting = settings[indexPath.row]
cell.SettingNameLabel.text = setting.name
cell.SettingCurrentLabel.text = String(format: "%.1f C", setting.CurrentSetting)
cell.SettingCurrentLabel.textAlignment = .Left
// Configure the cell...
//useTimer = true
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Setting Row \(indexPath.row) clicked")
performSegueWithIdentifier("Settings", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This works for me:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("works");
}
Add override before func maybe?

Swift - UITableView inside UIViewController, UITableView functions are not called

I inserted a tableview inside a UIViewController. But my code is not working. When I checked I found that none of the tableview functions are not called.
class CustomViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var authorArticlesTableView: UITableView!
var authorid: Int!
var authorname: String!
var articles: [JSON]? = []
func loadArticles(){
let url = "http:here.com/" + String(authorid) + "/"
println(url)
Alamofire.request(.GET, url).responseJSON { (Request, response, json, error) -> Void in
if (json != nil){
var jsonObj = JSON(json!)
if let data = jsonObj["articles"].arrayValue as [JSON]?{
self.articles = data
self.authorArticlesTableView.reloadData()
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadArticles()
println("viewDidLoad")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("numberOfRowsInSection")
return self.articles?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell
cell.articles = self.articles?[indexPath.row]
println("cellForRowAtIndexPath")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("WebSegue", sender: indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
Any solution for this?
Thanks,
You have to set your view controller as a table view delegate/datasource:
add to the end of the viewDidLoad:
authorArticlesTableView.delegate = self
authorArticlesTableView.dataSource = self
Set table delegate and dataSource :
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
Sometimes, if you forget to drap and drop UITableViewCell to UITableView. XCode don't understand TableView has Cell.
By default, when you drap and drop UITableView into UIViewController. I see UITableView has Cell. But you need to drap and drop UITableViewCell into UITableView also.
It is work with me.
Makes sense to do it in your
#IBOutlet weak var authorArticlesTableView: UITableView!
so it will become
#IBOutlet weak var authorArticlesTableView: UITableView! {
didSet {
authorArticlesTableView.delegate = self;
authorArticlesTableView.dataSource = self;
}
}

show textfields text in a UITableView using swift

I'm very new in swift programming .
I'm just trying some features of textfield .
just want to show textfields value in a UItableView.
stuck in this code
please check this out ....
and give solution
import UIKit
class langViewController: UIViewController {
var txt = ""
let simpleTableIdentifier = "TableViewCell";
#IBOutlet weak var txtlang: UITextField!
#IBOutlet weak var langTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func addButtonTapped(sender: AnyObject)
{
txt = txtlang.text
self.langTableView.reloadData()
langData.append(txt)
print(langData)
txtlang.resignFirstResponder()
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell
cell.textLabel?.text = txt
return cell;
}
To update your table view cells you have to call reloadData(). So you have to do something like this:
1. Declare the txt variable right where your class definition starts:
var txt = ""
2. In your button handler call reloadData() to update your cells.
#IBAction func addButtonTapped(sender: AnyObject) {
txt = txtlang.text
self.tableView.reloadData()
}
3. Set the text to your cell's label:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as! UITableViewCell
cell.textLabel?.text = txt
return cell;
}
thanks #flashadvanced
i was using a textfield and a tableview
i trying to get text in tableView from textfield. after suggestion of #flashadvanced i did it.
my code is :
class langViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{
var txt = ""
let simpleTableIdentifier = "TableViewCell";
#IBOutlet weak var txtlang: UITextField!
#IBOutlet weak var langTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.langTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.langTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return langData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.langTableView
.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = langData[indexPath.row]
return cell
}
#IBAction func addButtonTapped(sender: AnyObject)
{
txt = txtlang.text
langData.append(txt)
print(langData)
txtlang.resignFirstResponder()
self.langTableView.reloadData()
}

Resources