I have a UITableView that is supposed to have items in sections but only the first section (Science) in the array is appearing and I'm not sure what's wrong with it. It should be displaying both sections.
My code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var tableView: UITableView!
var checked = [Bool]()
let section = ["Science", "Math"]
let items = [["Physics", "Biology", "Chemistry"], ["Algebra I", "Algebra II", "Statistics"]]
override func viewDidLoad(){
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.allowsMultipleSelection = true
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.items[section].count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
// #warning Incomplete implementation, return the number of sections
return self.section.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return self.section[section]
}
//All before.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
//MARK: -Checkmark and save support.
cell.accessoryType = cell.isSelected ? .checkmark : .none
cell.selectionStyle = .none // to prevent cells from being "highlighted"
return cell
}
//MARK: - Checkmark and save functions.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
//MARK: - Sections
}
You made a mistake, wrong method. Let change numberOfSectionsInTableView(tableView:) to:
func numberOfSections(in tableView: UITableView) -> Int {
return self.section.count
}
In ViewDidLoad :
tableView.delegate = self
tableView.dataSource = self
Related
I'm getting this error message in my table view controller class
value of uitableviewcell has no member delegate
Here is an image of the error.
Is there anything that should be changed in my code?
import UIKit
class TViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var Tviews: UITableViewCell!
let contacts:[[String]] = [
["Elon Musk", "+1-201-3141-5926"],
["Bill Gates", "+1-202-5358-9793"],
["Tim Cook", "+1-203-2384-6264"],
["Richard Branson", "+1-204-3383-2795"],
["Jeff Bezos", "+1-205-0288-4197"],
["Warren Buffet", "+1-206-1693-9937"],
["The Zuck", "+1-207-5105-8209"],
["Carlos Slim", "+1-208-7494-4592"],
]
override func viewDidLoad() {
super.viewDidLoad()
Tviews.delegate = self
Tviews.datasource = self
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViews", for: indexPath)
print("\(#function) --- section = \(indexPath.section), row = \(indexPath.row)")
cell.textLabel?.text = contacts[indexPath.row][0]
return cell
}
You should assign your delegate and data source to your table view instance, and not your table view cell.
In order to do that, create an outlet link with your table view in the TViewController file and then edit your code like this:
import UIKit
class TViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
let contacts:[[String]] = [
["Elon Musk", "+1-201-3141-5926"],
["Bill Gates", "+1-202-5358-9793"],
["Tim Cook", "+1-203-2384-6264"],
["Richard Branson", "+1-204-3383-2795"],
["Jeff Bezos", "+1-205-0288-4197"],
["Warren Buffet", "+1-206-1693-9937"],
["The Zuck", "+1-207-5105-8209"],
["Carlos Slim", "+1-208-7494-4592"],
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.datasource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "<your-table-view-cell-id>", for: indexPath) as! YourTableViewCell
cell.textLabel?.text = contacts[indexPath.row][0]
return cell
}
}
I have a table view that is rendering some static data into a UITableView but occasionally when running on a physical device the data is replaced with ? (see screenshot). I have listed the code below if anyone has an idea why this is occurring?
Here is the code for the table view
import UIKit
class OvenViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension OvenViewController : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GridData.ovenTempConvArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: OvenCell.className, for: indexPath) as! OvenCell
let data = GridData.ovenTempConvArray[indexPath.row]
cell.lblFTemp.text = "\(data["f"] ?? "") F"
cell.lblCTemp.text = "\(data["c"] ?? "") C"
cell.lblGasMark.text = data["gm"]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
I am receiving 2 errors.
The first I am confused about because everything is inside the {} so I'm not sure where I am going wrong.
"Type 'StoriesViewController' does not conform to protocol
'UITableViewDataSource' Clicking fix adds:
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
<#code#>
}
and 2nd error
Ambiguous use of 'dequeueReusableCellWithIdentifier
I assigned the table cell the identifier "storyCell" from the main storyboard
Full code:
// creating a custom color
extension UIColor {
static var darkmodeGray = UIColor.init(red: 41/255, green: 42/255, blue: 47/255, alpha: 1)
}
class StoriesViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
<#code#>
}
#IBOutlet weak var tableView: UITableView!
let storySelection = [("WeekOne"),("WeekTwo"),("WeekThree"),("WeekFour"),("WeekFive"),("WeekSix")]
let storySelectionImages = [UIImage(named: "WeekOne"), UIImage(named: "WeekTwo"), UIImage(named: "WeekThree"), UIImage(named: "WeekFour"), UIImage(named: "WeekFive"), UIImage(named: "WeekSix")]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor .darkmodeGray
}
//Part One
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//Part Two
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storySelection.count
}
//Part Three
private func tableView(tableView :UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell=tableView.dequeueReusableCellWithIdentifier("storyCell", forIndexPath: IndexPath) as! TableViewCell
cell.CoverArt.image=self.storySelectionImages[indexPath .row]
return cell
}
}
Your code is Swift 2(!) code.
The usual way to update the signature of a method is to comment it out, retype it and use code completion.
Or read the documentation, that's always a good idea.
The three methods are (numberOfSections can be omitted if there is only one section)
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storySelection.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "storyCell", for: indexPath) as! TableViewCell
cell.CoverArt.image = self.storySelectionImages[indexPath.row]
return cell
}
I am using a UIViewController and a Table View/Table View Cell (extending to delegate/datasource). Whenever a cell is clicked from MessageController, it is supposed to be directed into another View Controller, called ChatController. Even though I am using didSelectRowAt and adding a segue with identifier, it does not switch to the ChatController.
import UIKit
class MessagesController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var myIndex = 0;
#IBOutlet weak var tableView: UITableView!
var tableData: [MModel] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
MData.getData { (data) in
self.tableData = data
self.tableView.reloadData()
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as! MessagesCell
cell.setup(model: tableData[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 375
}
//clicking on cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue", sender: nil)
}
}
The problematic line is as follows:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue", sender: nil)
}
You must set the delegate also in viewDidLoad
self.tableView.delegate = self
You have not set the delegate to the tableview.
Set it as:
aftertableView.dataSource = self
tableView.delegate = self
my problem had to do with having a GestureRecognizer in my viewDidLoad(). after so many hours of troubleshooting i realize that what was breaking the code was that 'hide keyboard' code of GestureRecognizer.
I want to make tableview cell have dynamic label or image in it. I don't want to loop add subview to content view of tableview cell because it will run slow when you scroll. So can anyone help me please? Like this image:
My code is;
Without knowing the context of your code, something like this can work:
NOTE This will work on iOS <= 8
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var TableVC: UITableView!
let elements = ["item1 item2 item3","item1 item2", "item1"]
override func viewDidLoad() {
super.viewDidLoad()
self.TableVC.delegate = self
self.TableVC.dataSource = self
self.TableVC.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.attributedText = addTextToAttribute(text: elements[indexPath.item])
return cell
}
func addTextToAttribute(text : String) -> NSMutableAttributedString {
let mutString = NSMutableAttributedString()
let s = text.components(separatedBy: .whitespaces)
let attr: [String: AnyObject] = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)]
for text in s {
mutString.append(NSAttributedString(string: "-" + text + "\n", attributes: attr))
}
return mutString
}
}