I have a tableView and I would like to show to the user a list of the languages, and the user can select one or more spoken languages. Is there a way for swift to show a list of it?
In yourTableViewControlloer
let langues = ["Mandarin","Spanish","English","Hindi","Arabic","Portuguese","Bengali","Russian","Japanese","Punjabi"]
Override following two function
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.textLabel?.text = langues[indexPath.row]
return cell
}
and
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let cell = tableView.cellForRowAtIndexPath(indexPath)
if (cell?.accessoryType == UITableViewCellAccessoryType.Checkmark){
cell!.accessoryType = UITableViewCellAccessoryType.None;
}else{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark;
}
}
This will give you the option to select multiple row item as follows
Related
I am trying out an exercise in creating a simple todo list.
Before introducing Realm or coreData i wanted to test it out and see if everyting is going smoothly.
I know i probably can make this work with some if conditions but i would love to be able to use the nil coalescing operator (i just love the simplicity of it), and i am not sure why its not working.
I made it work without it, but really interested what is the reason it is behaving like this.
When i launch the app it just shows "No Category Added" even after i add some items to the array and print them out, list stays the same.
import UIKit
class CategoriesTableView: UITableViewController {
var testData = [FauxData]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
// MARK: - Data Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData[indexPath.row].categoryTitle ?? "No Category Added"
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.count
}
#IBAction func addItem(_ sender: UIBarButtonItem) {
CreateNewItem(item: "test")
tableView.reloadData()
}
func CreateNewItem(item: String) {
let newItem = FauxData()
newItem.categoryTitle = item
testData.append(newItem)
print(item)
}
}
This is the class FauxData:
class FauxData {
var categoryTitle: String?
}
Sry if this is too simple or a duplicate, i wasn't able to find and appropriate answer.
Unfortunately, indexing an empty array crashes instead of returning nil, so you can't use the nil coalescing operator. Instead, use the .isEmpty property along with the ?: operator to achieve your goal:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData.isEmpty ? "No Category Added" : testData[indexPath.row].categoryTitle
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.isEmpty ? 1 : testData.count
}
Note: You have to return 1 from tableView(_:numberOfRowsInSection:) when the array is empty so that tableView(_:cellForRowAt:) will be called to return your default message.
If you implement safe array indexing, you could then use the nil coalescing operator:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData[safe: indexPath.row]?.categoryTitle ?? "No Category Added"
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.isEmpty ? 1 : testData.count
}
I want to make simple UITabelView. I registered it's cell with my custom class which named as backgroundviewcell. I want to get Label of the selected cell. I tried many times but the output is coming nil value. I have also tried solution from stack overflow but it does not work for me. This is my cellForRowAt indexPath code :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> backgroundViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "soundElementalcell") as! backgroundViewCell
let imageNames = sections[indexPath.section].images[indexPath.row]
cell.Labeltittle.text = sections[indexPath.section].items[indexPath.row]
cell.Labeltittle.textColor = UIColor(hex : 0x90BA27)
cell.LabelDetail.text = sections[indexPath.section].detail[indexPath.row]
//cell.detailTextLabel?.textColor = UIColor.red
//cell.isHighlighted = false
cell.backgroundColor = UIColor.clear
cell.iconview.image = UIImage(named: imageNames)
return cell
}
This is my didSelectRowAt indexPath code :
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)!
celltext = currentCell.textLabel!.text
performSegue(withIdentifier: "showPlayer", sender: self)
}
and my Segue Method is :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPlayer" {
let playerVC = segue.destination as! PlayerViewController
playerVC.trackName = (celltext)! as String
}
}
This is working for me:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! YourCellType
let labelContent = cell.labelToAccess.text
}
First line creates an instance of your cell type (or standard cell, not my case).
The second saves the content of your label (labelToAccess in this case) in a constant.
Instead of accessing the text from the cell's label you need to access the array that you have used to fill the tableView's cell data.
So you need to use UITableViewDelegate method didSelectRowAtindexPath and access the array that you are using with your tableView methods.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
//Access the array that you have used to fill the tableViewCell
print(yourArray[indexPath.row])
}
Note: Once confirm that TableView delegate is properly connected with your ViewController so that it will call didSelectRowAt method when you select cell.
Edit: If you want to pass the data then try like this way.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showPlayer", sender: indexPath) //Pass indexPath as sender instead of self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPlayer" {
let playerVC = segue.destination as! PlayerViewController
let indexPath = sender as! IndexPath
playerVC.trackName = sections[indexPath.section].items[indexPath.row]
}
}
Try this 'Swift 4' -
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCellTxt = yourTableView.cellForRow(at: indexPath)! as? YourCustomTableViewCell
print(currentCellTxt?.lblYourName?.text) // 'lblYourName' that you defined in your 'YourCustomTableViewCell'
}
You didn't set any text for textLabel. Hence it returns nil value.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> backgroundViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "soundElementalcell") as! backgroundViewCell
let imageNames = sections[indexPath.section].images[indexPath.row]
cell.Labeltittle.text = sections[indexPath.section].items[indexPath.row]
cell.Labeltittle.textColor = UIColor(hex : 0x90BA27)
cell.LabelDetail.text = sections[indexPath.section].detail[indexPath.row]
//cell.detailTextLabel?.textColor = UIColor.red
//cell.isHighlighted = false
cell.backgroundColor = UIColor.clear
cell.iconview.image = UIImage(named: imageNames)
return cell
}
In didSelectRow func try to get value from Labeltittle.text not from textLabel.text
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)!
celltext = currentCell.Labeltittle.text
performSegue(withIdentifier: "showPlayer", sender: self)
}
I updated Xcode and since then I'v problems with my dataBase.
code:
override func numberOfSections(in tableView: UITableView) -> Int {
// return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// return the number of rows
return leadItems.count
}
func cellForRow(at indexPath: IndexPath) -> UITableViewCell?
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! LeadsTableViewCell
// Configure the cell...
cell.user_name_label.text = leadItems[indexPath.row].user_name
cell.school_name_label.text = leadItems[indexPath.row].school_name
return cell
}
The error that I get is:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, -64}; contentSize: {375, 65802}>) failed to obtain a cell from its dataSource ()
Your method name for cellForRow is not correct.
Replace this line
func cellForRow(at indexPath: IndexPath) -> UITableViewCell?
{
with
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
Add this to your viewDidLoad method:
tableView.register(LeadsTableViewCell.self, forCellReuseIdentifier: "Cell")
This is assuming you don't have a prototype cell in the tableView in your storyboard. If you do have a prototype cell, ensure the Reuse Identifier is "Cell" and the custom class of the cell is LeadsTableViewCell; then there'll be no need to register the cell.
UPDATE
I just noticed your method name is wrong, it should be:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! LeadsTableViewCell
// Configure the cell...
cell.user_name_label.text = leadItems[indexPath.row].user_name
cell.school_name_label.text = leadItems[indexPath.row].school_name
return cell
}
In order to get a cell for your table view you must implement the data source method that is designed to provide the table view with a cell for a given row at an index path. This method is:
tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
Because this method is a required method you can not leave it out or you will get an error. Configure your cell in this method.
I have an Array of objects like this:
var Dogs : [Dog] = [Dog]()
To give you an example it looks like this when you print it :
[Dog {
name = Dog1;
age = 9;
}, Dog {
name = Dog2;
age = 4;
}]
I want to show this element in a Table View so I use this classical function :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.titleLabel.text = Dogs[indexPath.row]["name"]! as? String
return cell
}
But I get an ERROR :
fatal error: Array index out of range
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let dog = Dogs[indexPath.row]
cell.titleLabel.text = dog.name
return cell
}
I have static table and I set background color for tableview -> tableView.backgroundColor = UIColor.redColor() and when I have etc. 3 rows in static table then is tableview colored and 3 rows are white how can I fix background color for this cells? This code are not working for static
table ->
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = numbers[indexPath.row]
cell.backgroundColor = UIColor.greenColor()
return cell
}
In static Table View you don't have to implement cellForRowAtIndexPath. So I suggest you to implement the following code:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// Change the color of all cells
cell.backgroundColor = UIColor.greenColor()
}
Please don't use the cellForRowAtIndexPath method in this case because as you said you are using a static tableview.
Now coming to the solution. Today I just went through the same problem and the scenario was almost same as yours.
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor .grayColor()
}
One more thing I just wanna tell you that as per Apple's Document all the cell's default color is clear/white. So if you are trying to set the color through the Interface Builder or cellForRowAtIndexPath method it will return the white color by default if you are using iOS 7 / iOS 8 / iOS 9. So instead of declaring inside cellForRowAtIndexPath method use the above code. It will work fine.
Thanks
Hope this helped.
First of all make sure each cell has the background colour set to default in the UI mode. under the inspector attributes. Then in the code set
cell.backgroundcolor = UIColor.clearcolor()
Cheers
Sam
UITableViewCell.appearance().backgroundColor = UIColor.greenColor()
you can change the contentView background as it is a subview of cell:
cell.contentView.backgroundColor = UIColor.greenColor()
For swift 4:
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if _isAccountNotSet {
print("_isAccountNotSet\(_isAccountNotSet)")
cell.backgroundColor = .groupTableViewBackground
} else {
print("_isAccountNotSet\(_isAccountNotSet)")
cell.backgroundColor = .white
}
}
To change the background color of an intended row or rows use the following code:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
if indexPath.row == 2
{
cell.contentView.backgroundColor = UIColor.lightGray
}
}
This code changes the background color at IndexPath 2 (the third row.) You could change the 2 to which ever number you'd like or make it a list of numbers like so:
if indexPath.row == 2 || indexPath.row == 7
{
cell.contentView.backgroundColor = UIColor.lightGray
}
you could also sub in a variable instead of the 2 to make it more dynamic.
Good Luck!