Table view cell not showing in table view controller - ios

I'm new to swift and I'm trying to get my cells to show in tableView. I searched for questions here but none could help. The table loads fine and I get no errors regarding the tableView. Is there something I'm missing?
-I've double-checked the reuse identifier, they are the same
-I removed and readied the outlets
Here is my UITableViewController class:
class DrawerViewController: UITableViewController{
#IBOutlet weak var drawerTable: UITableView!
var currentCell = [DrawerModel]()
override func viewDidLoad() {
super.viewDidLoad()
addGradientToView(view: drawerTable)
let temp2Model = DrawerModel()
temp2Model.item = "Profile"
temp2Model.icon = "loginbackground2.jpg"
currentCell.append(temp2Model)
drawerTable.delegate = self
drawerTable.dataSource = self
//self.drawerTable.separatorStyle = UITableViewCellSeparatorStyle.none
//self.drawerTable.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = drawerTable.dequeueReusableCell(withIdentifier: "drawerCell", for: indexPath) as! DrawerTableViewCell
let tempModel: DrawerModel
tempModel = currentCell[indexPath.row]
cell.thisLabel.text = tempModel.item
print("test1" + tempModel.item! as Any)
let currentImage = UIImage(named: "loginbackground2.jpg")
cell.thisImage = UIImageView(image: currentImage)
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("it ran")
return currentCell.count
}
func addGradientToView(view: UITableView)
{
//gradient layer
let gradientLayer = CAGradientLayer()
//define colors
gradientLayer.colors = [UIColor.init(rgb: 0x4b0082).cgColor, UIColor.init(rgb: 0xfa8072).cgColor]
//define locations of colors as NSNumbers in range from 0.0 to 1.0
//if locations not provided the colors will spread evenly
gradientLayer.locations = [0.0, 0.8]
//define frame
gradientLayer.frame = view.bounds
//insert the gradient layer to the view layer
view.layer.insertSublayer(gradientLayer, at: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is my UITableViewCell class:
class DrawerTableViewCell: UITableViewCell {
#IBOutlet weak var thisImage: UIImageView!
#IBOutlet weak var thisLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

If you are using UITableViewController (in your case DrawerViewController) it already have a tableView property embedded, which have a delegate and dataSource set to controller.
So when in your case next lines are redundant
drawerTable.delegate = self
drawerTable.dataSource = self
To fix just call tableView.reload() after currentCell.append(temp2Model)

Related

design UI of app using tablview in swift

I want UI of my app to be similar like as shown in below image.
Using tableview i'm able to get Payment,Delivery,Build Team options as shown in image but for Build Profile,Manage Menu.. how do i do it using tableview ?
If not tableview for these options then what other control i can try.
this type of UI you are looking for and you can easily get by creating different Cell classes
UI Output :
Required Code
Step 1 - Create different Xib of table cell
class viewWithArrow: UITableViewCell {
#IBOutlet weak var headerLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class viewWithShadow: UITableViewCell {
#IBOutlet weak var shadowView: UIView!{
didSet{
shadowView.addShadowToView(color: .black)
}
}
#IBOutlet weak var headerLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Adding Shadow Effect :
extension UIView {
func addShadowToView(color:UIColor)
{
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = 0.2
self.layer.masksToBounds = false
self.clipsToBounds = false
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 5
}
}
View controller
class ViewController: UIViewController
{
var dataArray : [String] = ["11","22","33","44","55","66"]
#IBOutlet weak var homeVcTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
homeVcTableView.register(UINib(nibName: "viewWithShadow", bundle: nil), forCellReuseIdentifier: "viewWithShadow")
homeVcTableView.register(UINib(nibName: "viewWithArrow", bundle: nil), forCellReuseIdentifier: "viewWithArrow")
}
override func viewWillAppear(_ animated: Bool) {
self.homeVcTableView.delegate = self
self.homeVcTableView.dataSource = self
}
}
extension ViewController : UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0,1:
let cell = self.homeVcTableView.dequeueReusableCell(withIdentifier: "viewWithShadow", for: indexPath) as! viewWithShadow
cell.headerLabel.text = dataArray[indexPath.row]
return cell
default:
let cell = self.homeVcTableView.dequeueReusableCell(withIdentifier: "viewWithArrow", for: indexPath) as! viewWithArrow
cell.headerLabel.text = dataArray[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.homeVcTableView.frame.size.height*0.1
}
}
Working code link - https://drive.google.com/open?id=18mSlWAU_e4XElox4H-oTpqg8clD_HKwu

I can't display TableView in added subview

I have a ViewController named LiveMatchVC. I want to show another ViewController(named LiveMatchMomentsVC and it has a TableView) in LiveMatchVC.
I added a subview and I displayed LiveMatchMomentsVC in LiveMatchVC, but I can't view the TableView of the LiveMatchMoments in LiveMatchVC.
My codes and screenshots are as below.
How can I solve this problem?
White area is my TableView in LiveMatchMomentsVC
LiveMatchVC Codes
class LiveMatchVC: UIViewController {
//---------Outlets-----------
#IBOutlet weak var imgLiveMatchScoreBG: UIImageView!
#IBOutlet weak var openLeft: UIBarButtonItem!
let titleCont1 = TZSegmentedControl(sectionTitles: ["Maç Raporu","Canlı Anlatım", "Önemli Olaylar", "İstatistikler", "Kadrolar" ])
override func viewDidLoad() {
super.viewDidLoad()
let liveMatchMomentsVC = storyboard?.instantiateViewController(withIdentifier: "LiveMatchMomentsVC") as! LiveMatchMomentsVC
titleCont1.indexChangeBlock = { (index) in
if self.titleCont1.selectedSegmentIndex == 1 {
self.view.addSubview(liveMatchMomentsVC.view)
liveMatchMomentsVC.view.frame = CGRect(x: 0, y: self.imgLiveMatchScoreBG.frame.height+self.titleCont1.frame.height, width: self.view.frame.width, height: self.view.frame.height-44)
self.addChildViewController(liveMatchMomentsVC)
self.view.addSubview(liveMatchMomentsVC.view)
self.didMove(toParentViewController: self)
}
}
}
}
LiveMatchMomentsVC Codes
import UIKit
class LiveMatchMomentsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblLiveMatch: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override 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 15
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MatchEvent", for: indexPath) as! MatchEventTableViewCell
cell.lblMatchEventTime.text = "69"
cell.lblMatchEvent.text = "Goal. Juraj Kucka"
return cell
}
}

Swift - UIView inside custom UITableViewCell won't update buttons/labels

I'm just getting started with Swift and I'm having some weird issues with a custom UITableViewCell. The issue is I needed to have a white background inside each table cell as seen here.
I have created a custom UITableViewCell class and created IBOutlets for a image, label and button as shown below:
import UIKit
class LocationTableViewCell: UITableViewCell {
#IBOutlet var locationImageView: UIImageView!
#IBOutlet var locationButton: UIButton!
#IBOutlet var locationLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
My view controller code is:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet var locationTableView: UITableView!
var skiLocation = Location(name: "Banff", picture: UIImage(named: "ski.jpeg")!)
var tundraLocation = Location(name: "Yellowknife", picture: UIImage(named: "tundra.jpeg")!)
var beachLocation = Location(name: "Cancun", picture: UIImage(named: "beach.jpeg")!)
var locations: [Location] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: LocationTableViewCell = tableView.dequeueReusableCellWithIdentifier("location", forIndexPath: indexPath) as! LocationTableViewCell
cell.locationLabel.text = self.locations[indexPath.row].name
cell.locationImageView.image = self.locations[indexPath.row].picture
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locations = [skiLocation, tundraLocation, beachLocation]
self.locationTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have approached this problem by making a UIView inside of each table view and then placing the button, label and image inside the UIView. This was just to get the white background. However, when I run my code everything shows as expected, except there is no UILabel and the UIButton is stylized as per storyboard. When I try to change the background of the label, or the button via storyboard, nothing changes. No label and just the generic button. The weird part is I am able to set the images to the UIImageView via the ViewController class.
Any thoughts?
EDIT: Here is the link to the storyboard view. I have used the identifier field in the storyboard view to link the cell.
You have UITableViewDataSource But UITableViewDelegateis missing.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var locationTableView: UITableView!
var skiLocation = Location(name: "Banff", picture: UIImage(named: "ski.jpeg")!)
var tundraLocation = Location(name: "Yellowknife", picture: UIImage(named: "tundra.jpeg")!)
var beachLocation = Location(name: "Cancun", picture: UIImage(named: "beach.jpeg")!)
var locations: [Location] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: LocationTableViewCell = tableView.dequeueReusableCellWithIdentifier("location", forIndexPath: indexPath) as! LocationTableViewCell
cell.locationLabel.text = self.locations[indexPath.row].name
cell.locationImageView.image = self.locations[indexPath.row].picture
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locations = [skiLocation, tundraLocation, beachLocation]
self.locationTableView.dataSource = self
self.locationTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

How to access one controller variable and methods from other controller in swift correctly?

I create uiSegmentedControl in HomePageViewController. There are two items in segmented control. When I select first item , I add sensorItemViewController content as a subview in HomePageViewController with displayContentController method. And when clicked second item, I want to access methods of SensorTabItemViewController class which it's name is reloadMyTableView from HomePageViewConroller. I accessed from sensorItemVC but I get "unexpectedly found nil while unwrapping an Optional value" exception. How can access SensorItemTabViewController from HomePageViewControler correctly ? Thank you all response
HomePageViewController.swift :
let segmentedControlItems = ["Table", "RefreshTableView"]
var viewControllerArray: Array<UIViewController> = []
var segmentedControl : UISegmentedControl!
var sensorItemVC: SensorTabItemViewController!
class HomePageViewController: UIViewController,UIScrollViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl=UISegmentedControl(items: segmentedControlItems)
segmentedControl.selectedSegmentIndex=0
segmentedControl.tintColor=myKeys.darkBlueColor
segmentedControl.layer.cornerRadius = 0.0;
segmentedControl.layer.borderWidth = 1.5
segmentedControl.frame=CGRectMake(0, frameHeight/2, frameWidth, 35)
segmentedControl.addTarget(self, action: "changeSegmentedControlItem", forControlEvents: .ValueChanged)
self.view.addSubview(segmentedControl)
let sensorItemViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sensorTabItemViewController")
viewControllerArray.append(sensorItemViewController)
}
func changeSegmentedControlItem(){
print(segmentedControl.selectedSegmentIndex)
if(segmentedControl.selectedSegmentIndex==0){
displayContentController(viewControllerArray[0])
}
else{
sensorItemVC.reloadMyTableView("Temp value", light: "Light value", noise: "noise Value", motion: "motion Value")
}
}
func displayContentController (content:UIViewController) {
self.addChildViewController(content)
print(self.segmentedControl.frame.height)
content.view.frame=CGRectMake(0, self.frameHeight/2+self.segmentedControl.frame.height, self.frameWidth,
self.frameHeight-(segmentedControl.frame.height*2+self.frameHeight/2))
self.view.addSubview(content.view)
content.didMoveToParentViewController(self)
}
}
SensorTabItemViewController. swift as below :
class SensorTabItemViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let sensorName=["Sıcaklık Sensörü","Işık Sensörü","Gürültü Sensörü","Hareket Sensörü"]
var sensorDetails=["","","",""]
var sensorImages: Array<UIImage> = []
override func viewDidLoad() {
super.viewDidLoad()
print("sensorTab")
let tempImg=UIImage(named: "temp_ic") as UIImage?
let lightImg=UIImage(named: "light_ic") as UIImage?
let noiseImg=UIImage(named: "noise_ic") as UIImage?
let motionImg=UIImage(named: "motion_ic") as UIImage?
sensorImages.append(tempImg!)
sensorImages.append(lightImg!)
sensorImages.append(noiseImg!)
sensorImages.append(motionImg!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadTableView(){
sensorDetails=[]
sensorDetails.append(temp)
sensorDetails.append(light)
sensorDetails.append(noise)
sensorDetails.append(motion)
tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sensorName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("sensorCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text=sensorName[indexPath.row]
cell.imageView?.image=sensorImages[indexPath.row]
cell.detailTextLabel?.text=sensorDetails[indexPath.row]
return cell
}
}
You never set the value of sensorItemVC. That is why it is nil. I guess that
let sensorItemViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sensorTabItemViewController")
should be replaced with
sensorItemVC = self.storyboard!.instantiateViewControllerWithIdentifier("sensorTabItemViewController") as! SensorTabItemViewController

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?

Resources