I'm having an issue trying to connect my UITableView with my UIViewController2 in storyboard mode. I've made a UITableView within my UIViewController. When I click on the any of the cells I want it to go to the UIViewController2. This view isnt connected to anything other then giving it a class and storyboard ID in the identity inspector. When I try to call that class when I press on a cell it becomes a black screen and nothing I put in the UIViewController2 in storyboard is visible. Why is that? Here is some of the code I tried by to no avail. Please let me know if this isnt clear enough. Thank you!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return featCatNames.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = featCatNames[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let mainStoryboard = UIStoryboard(name: "finalBusVC", bundle: NSBundle.mainBundle())
let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("finalBusV") as UIViewController
//let finaBus = self.storyboard?.instantiateViewControllerWithIdentifier("finalBusV") as finalBusVC
//self.navigationController?.pushViewController(finalBusVC(), animated: true)
}
Related
I'm still fairly new to swift, and I'm trying to create a tableview in a xib, attaching it to a swift file, but then I want to populate it using another swift file. I also have have another xib for the custom table cell. What I am trying right now does not work.
A section of the ViewController class:
var testArray = ["test", "test1","test2","test3","test4"]
var pages : [dataViewController]{
get {
let page1: dataViewController = Bundle.main.loadNibNamed("dataView", owner: self, options: nil)?.first as! dataViewController
page1.backgroundColor = UIColor(white: 1, alpha: 0)
page1.tookClassTable.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "tookClassCell")
page1.tookClassTable.delegate = self
page1.tookClassTable.dataSource = self
return [page1]
}
}
// TableView functions
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tookClassCell", for: indexPath) as! TableViewCell
cell.tookClassCell.text = testArray[indexPath.row]
print(testArray[indexPath.row])
return cell
}
Basically, I made a paging type view, such as the iOS home screen, and have page1 and page2. In page1, there is a tableView, and registered the tableViewCell and used cellForRowAt to try to populate the table. There are no errors, but the table is just blank.
Does anyone know how to populate this tableView? Thanks in advance!
I can't figure why it can't redirect to another View Controller when I click on a TableViewCell
FirstViewController is the view controller that contains the tableView
SecondViewController is my desination
What I already done:
1) I embedded FirstViewController in a NavigationController in StoryBoard
2) I already set up show segue from FirstViewController to SecondViewController, and already set the segue identifier to "GoToSecondViewController"
Of course in order for me to show the data in the tableViewCell I have this 2 function:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myCell.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCellClass
cell.myCellList = self.myCell[indexPath.row]
return cell
}
3) In FirstViewController, I already try for below 2 solution:
First solution:
I call performSegue in didSelectRowAt function
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "GoToSecondViewController", sender: self)
}
Second solution:
I use navigationController?.pushViewController in didSelectRowAt function
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.navigationController?.pushViewController(controller, animated: true)
}
Above 2 solution I tried, but didn't produce any result. After looking at this question, I even disable my gestureRecognizer in FirstViewController, still cant redirect to SecondViewController
So I finally just wanna to print out the value by this,but also no value printing out in console:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("section: \(indexPath.section)")
print("row: \(indexPath.row)")
}
That all I tried in order to redirect to another view controller when click on tableViewCell, but still not working.What I missing here?
add this line in viewDidLoad
tableview.delegate = self
I finally figure it out,I need to check the Single Selection option for TableView in StoryBoard.
Like this:
Previously I set the Selection to No Selection.Therefore causing the problem above.
there is a class MenuViewController in which the array recorded in the table is recorded:
import Foundation
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var menuTableView: UITableView!
let myTitle = ["Помощь", "Информация", "Поддержка"]
override func viewDidLoad() {
super.viewDidLoad()
menuTableView.delegate = self
menuTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myTitle.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = menuTableView.dequeueReusableCell(withIdentifier: "MenuCell") as! MenuTableViewCell
cell.labelText.text = myTitle[indexPath.row]
return cell
}
}
What do you need to write in it to go to Info Controller?
I assume you are using storyboards. First you need to set up some sort of connection between your two viewcontrollers. You can do this by setting up a "segue". You hold ctrl+click drag from the first viewcontroller to the 2nd viewcontroller. It looks like this:
When you let go of the mouse, you will see this:
Click on Show. Now you will have created a segue.
Now you need to name it. So click on the segue that shows up in the storyboard. It is basically just an arrow from the Menu View Controller to the Info View Controller. On the right hand side you will see a place where you can name it (give it an identifier):
Now ... you have done all you needed to do in the storyboard. Now in your actual code in the MenuViewController, you need to associate clicking the tableviewcell. You do this by using the delegate method didSelectRowAt.
I see you have already set up the delegate with this line:
menuTableView.delegate = self
That ensures that didSelectRowAt will be called whenever the user taps on a row.
So now what you want to do is write the code to perform the segue:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "YourSegueName", sender: self)
}
Note:
Here is more information on interacting with a tableview row:
How to detect tableView cell touched or clicked in swift
Here is more information about segues:
IOS - How to segue programmatically using swift
There are many more customizations you can do ... such as passing data through to the next viewcontroller via the segues. Here's how:
Pass data through segue
implement UITableViewDelegate method:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//To InfoViewController I am considering you have created InfoViewController with XIB
let controller = InfoViewController(nibName: "YourNibName", bundle: nil)
//Present Your Controller
self.present(controller, animated: true) {
}
//Push Your controller if your view is already part of NavigationController stack
self.navigationController?.pushViewController(controller, animated: true)
}
Just add a
nextViewController.didMove(toParentViewController: self) inside a
"didSelectRowAt". Example given below.
This is for List a tableview cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! PatientFamilyDetailTableViewCell
cell.txt_patientName.text = patientname[indexPath.row]
// Configure the cell...
return cell
}
Now it's for Select a Table view cell:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
if cell.isSelected {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "medtestmain") as! medTest
patient_id = relation[indexPath.row]
patient_name = patientname[indexPath.row]
UserDefaults.standard.set(patient_id, forKey: "patient_id")
UserDefaults.standard.set(patient_name, forKey: "patient_name")
self.addChildViewController(nextViewController)
nextViewController.view.frame = self.view.frame
self.view.addSubview(nextViewController.view)
nextViewController.didMove(toParentViewController: self)
}
}
}
I have a TableViewController with static cells
I tried both creating segue from TableViewController and TableView cell (Not at the same time)
However, in both scenario, didSelectRowAtIndexPath was not fired
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("select")
}
I also have embedded collectionviewcontroller
class EventDetail: UITableViewController, UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
What may be causing this?
Check your tableview selection must be single selection, if it is "No selection" then didSelectedRowAtIndex would not get called.
You can download sample code and observe it.
Sample download
Also check
Ideally your cellForRowAtIndex should be like this
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : CustomCell! = tableView.dequeueReusableCellWithIdentifier("ID_CustomCell", forIndexPath: indexPath) as! CustomCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.lblData.text = "CustomCell....."
return cell
}
Swift 4 code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : CustomCell! = tableView.dequeueReusableCell(withIdentifier: "ID_CustomCell", for: indexPath) as! CustomCell
cell.selectionStyle = .none
cell.lblData.text = "CustomCell....."
return cell
}
call performseguewithidentifier from didselectRow if you have created segue from tableviewcontroller. like,
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("select")
self.performSegueWithIdentifier("your segue identifier", sender: self)
}
hope this will help :)
So i am trying to get the value of the textLabel of the row I select. I tried printing it, but it didn't work. After some research I found out that this code worked, but only in Objective-C;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"did select and the text is %#",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
}
I could not find any solution for Swift. Printing the indexpath.row is possible though, but that is not what I need.
so what should I do? or what is the 'Swift-version' of this code?
Try this:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
If you're in a class inherited from UITableViewController, then this is the swift version:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
NSLog("did select and the text is \(cell?.textLabel?.text)")
}
Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
let text = cell?.textLabel?.text
if let text = text {
NSLog("did select and the text is \(text)")
}
}
Swift 4
To get the label of the selected row:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
To get the label of the deselected row:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
If you want to print the text of a UITableViewCell according to its matching NSIndexPath, you have to use UITableViewDelegate's tableView:didSelectRowAtIndexPath: method and get a reference of the selected UITableViewCell with UITableView's cellForRowAtIndexPath: method.
For example:
import UIKit
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
switch indexPath.row {
case 0: cell.textLabel?.text = "Bike"
case 1: cell.textLabel?.text = "Car"
case 2: cell.textLabel?.text = "Ball"
default: cell.textLabel?.text = "Boat"
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
print(selectedCell?.textLabel?.text)
// this will print Optional("Bike") if indexPath.row == 0
}
}
However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array of String) according to a NSIndexPath. By doing things like this, you will separate each element's responsibilities.
Thereby, this is what I would recommend:
import UIKit
class TableViewController: UITableViewController {
let toysArray = ["Bike", "Car", "Ball", "Boat"]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toysArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = toysArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let toy = toysArray[indexPath.row]
print(toy)
// this will print "Bike" if indexPath.row == 0
}
}
As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell inside tableView:didSelectRowAtIndexPath: in order to print the desired text.
In my case I made small changes, when i search the value in tabelview select (didSelectRowAtIndexPath) the cell its return the index of the cell so im get problem in move one viewControler to another.By using this method i found a solution to redirect to a new viewControler
let indexPath = tableView.indexPathForSelectedRow!
let currentCellValue = tableView.cellForRow(at: indexPath!)! as UITableViewCell
let textLabelText = currentCellValue.textLabel!.text
print(textLabelText)
In swift 4 :
by overriding method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name : "Main", bundle: nil)
let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController
self.navigationController?.pushViewController(prayerVC, animated: true)
}
This will work:
let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
Maintain an array which stores data in the cellforindexPath method itself :-
[arryname objectAtIndex:indexPath.row];
Using same code in the didselectaAtIndexPath method too.. Good luck :)