swift: How to set UITableViewCell display fullscreen with InfiniteScrolling (allow paging) - ios

I have a custom UITableView with infinite Scroll and Paging Enable. Each of my cells has UIImageView on background, I want each time I scroll up or down it will display each image as full screen.
I used this function for full screen, but my view is not full screen after one time infinite scroll.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.frame.size.height
}

Late Answer, Might help to others.
For Full-screen Paging of your TableViewcell. Follow the below steps.
(Consider as Without navigation bar)
TableView constrain should be with superview (not safeArea) in allside with 0 constant.
configure your Tableview like below.
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
private func configureTableView() {
tableView.rowHeight = UIScreen.main.bounds.height
tableView.estimatedRowHeight = UIScreen.main.bounds.height
tableView.separatorStyle = .none
tableView.isPagingEnabled = true
tableView.bounces = false
tableView.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.estimatedSectionFooterHeight = CGFloat.leastNormalMagnitude
tableView.sectionFooterHeight = CGFloat.leastNormalMagnitude
tableView.contentInsetAdjustmentBehavior = .never
tableView.delegate = self
tableView.dataSource = self
}

Please find below source code in which you will get table view scrolling along with the different images.
Swift 4
//
// ImageTVC.swift
//
// Created by Test User on 06/02/18.
// Copyright © 2018. All rights reserved.
//
import UIKit
class ImageTVC: UITableViewCell {
#IBOutlet weak var imgView: UIImageView!
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
}
}
//
// TableViewVC.swift
//
// Created by Test User on 06/02/18.
// Copyright © 2018. All rights reserved.
//
class TableViewVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension TableViewVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
//----------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageTVC
if indexPath.item % 2 == 0 {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 2)/255.0, green: CGFloat(indexPath.item * 0)/255.0, blue: CGFloat(indexPath.item * 0)/255.0, alpha: 1.0)
} else if indexPath.item % 3 == 0 {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 0)/255.0, green: CGFloat(indexPath.item * 2)/255.0, blue: CGFloat(indexPath.item * 0)/255.0, alpha: 1.0)
} else {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 0)/255.0, green: CGFloat(indexPath.item * 0)/255.0, blue: CGFloat(indexPath.item * 2)/255.0, alpha: 1.0)
}
print("IndexPath.row = \(indexPath.row)")
return cell
}
//----------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.bounds.size.height
}
}
Also find storyboard design.

Related

Swift Xcode TableViewCell's Not Loading First Time

I have a Button which Segues to my TableViewController and when I click the button for the first time, the TableView Doesn't Load but when I go back and click again, my Data Loads.
I tried to set the breakpoints but the tableview functions don't load? Any reason for this?
EDIT:
This is my Code For The TableView, if any other code is required tell me.
class ServicesDisplay: UITableViewController {
#IBOutlet var MainTitle: UILabel!
#IBOutlet var image: UIImageView!
let db = Firestore.firestore()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
performSegue(withIdentifier: "seque", sender: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 260
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let jsonFbPic = (jsonFile["SecondScreen"])
let test = ((jsonFbPic["Services Image"]))
let count = ((test["Image\(myIndex)"]))
if count.count == 0 {
return serviceTextArray.count
} else {
return count.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomServicesCell
cell.serviceText?.text = serviceTextArray[indexPath.row]
//Variables
let Json = jsonFile["SecondScreen"]
let MainTitleJson = Json["Text"]
let MainTitleSize = CGFloat(Int("\(MainTitleJson["Size"])")!)
//Main Title:
cell.serviceText.font = UIFont(name: "\(MainTitleJson["Font"])", size: MainTitleSize)
cell.serviceText.textColor = hexStringToUIColor(hex: "\(MainTitleJson["Color"])")
cell.serviceImage?.loadImagesFromCacheWithUrlString(myIndex: indexPath.row, labelName: serviceTextArray[indexPath.row], CellImage: cell.serviceImage)
cell.selectionStyle = .none
return cell
}
public func hexStringToUIColor(hex: String) -> UIColor {
var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
var rgbValue: UInt64 = 0
if cString.hasPrefix("#") {
cString.remove(at: cString.startIndex)
} else if cString.count != 6 {
return UIColor.black
}
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat((rgbValue & 0x0000FF)) / 255.0, alpha: CGFloat(1.0))
}
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.reloadData()
})
}
override func viewDidAppear(_ animated: Bool) {
}
// MARK: - Table view data source
}
Sorry for posting it as an answer but I am also new to stackOverFlow. It Is happening because you are performing segue before the data is fetched from the server. Perform segue as a completion after data fetch is completed. Please let me know if that was a case!

Making custom UITableView Cells Display Contents Properly (Not Blank)

I have been working on making an iOS app which requires a screen/view that is scrollable and has an image, then a list and then an image and then another image (attached is the screenshot from the Android version I made)
Top of the view
View Scrolled
I have tried using the following code, which gives me the correct amount of cells but they are all blank.
//
// ServicesTableViewController.swift
// Contact Australis
//
// Created by Raghav Khanna on 22/4/18.
// Copyright © 2018 Australis. All rights reserved.
//
import UIKit
class ServiceViewCell: UITableViewCell {
#IBOutlet weak var IMage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
IMage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServiceViewCellList: UITableViewCell {
#IBOutlet weak var somethin_label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
let radius: CGFloat = 5
let border_width:CGFloat = 1.5
somethin_label.layer.borderColor = color
somethin_label.layer.borderWidth = border_width
somethin_label.layer.cornerRadius = radius
somethin_label.backgroundColor = back_colour_ui
}
var items_maintenance = ["Painting","All Lighting & Globe Replacemt",
"Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
} class ServiceViewCellCleaning: UITableViewCell {
#IBOutlet weak var Title: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
Title.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServiceViewCellCleaningList: UITableViewCell {
#IBOutlet weak var other_label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
let radius: CGFloat = 5
let border_width:CGFloat = 1.5
other_label.layer.borderColor = color
other_label.layer.borderWidth = border_width
other_label.layer.cornerRadius = radius
other_label.backgroundColor = back_colour_ui
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServicesTableViewController: UITableViewController {
let basicCellIdentifier = "BasicCell"
var items_maintenance = ["Painting","All Lighting & Globe Replacement", "Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
var items_cleaning = ["All Genral Comercial Cleaning","Office Cleaning", "Initial Clean","Spring Clean","Steam Carpet Cleaning","Window Washing","High Pressure Washing", "Waste Removal", "Strip & Seal Hard Floors", "Scrubbing & Buffing Hard Floors"]
let cellSpacingHeight: CGFloat = 5
#IBOutlet var table: UITableView!
func configureTableView() {
//tableView.rowHeight = UITableViewAutomaticDimension
//tableView.estimatedRowHeight = 1000.0
//let rect = CGRect(origin: .zero, size: CGSize(width: 400, height: 400))
//self.tableView = UITableView(frame: rect, style: UITableViewStyle.plain)
table.register(ServiceViewCell.self, forCellReuseIdentifier: "maintenance")
table.register(ServiceViewCellList.self, forCellReuseIdentifier: "customcell")
table.register(ServiceViewCellCleaning.self, forCellReuseIdentifier: "cleaning")
table.register(ServiceViewCellCleaningList.self, forCellReuseIdentifier: "cleaning_customcell")
}
/*func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return
}*/
override func viewDidLoad() {
super.viewDidLoad()
self.configureTableView()
table.reloadData()
table.delegate = self
table.dataSource = self
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return items_maintenance.count
} else if section == 2 {
return 1
}
else {
return items_cleaning.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let maintenance_title = table.dequeueReusableCell(withIdentifier: "maintenance", for: indexPath) as! ServiceViewCell
let maintenance_list = table.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! ServiceViewCellList
let cleaning_title = table.dequeueReusableCell(withIdentifier: "cleaning", for: indexPath) as! ServiceViewCellCleaning
let cleaning_list = table.dequeueReusableCell(withIdentifier: "cleaning_customcell", for: indexPath) as! ServiceViewCellCleaningList
maintenance_list.somethin_label?.text = self.items_maintenance[indexPath.row]
maintenance_list.somethin_label?.adjustsFontSizeToFitWidth = false
maintenance_list.somethin_label?.font = UIFont.systemFont(ofSize: 10.0)
cleaning_list.other_label?.text = "test"
cleaning_list.other_label?.adjustsFontSizeToFitWidth = false
cleaning_list.other_label?.font = UIFont.systemFont(ofSize: 10.0)
cleaning_title.Title?.image = UIImage(named: "cleaning.png")
maintenance_title.IMage?.image = UIImage(named: "maintenance.png")
if indexPath.section == 0 {
return maintenance_title
} else if indexPath.section == 1 {
return maintenance_list
} else if indexPath.section == 2 {
return cleaning_title
}
else {
return cleaning_list
}
return cleaning_list
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
//Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
My Storyboard looks like this (Its another view in the main storyboard with for prototype cells with custom classes) and I am struggling to figure out why I keep getting either "Unexpectedly found nil while unwrapping an Optional value" for "maintenance_list.somethin_label!.text = self.items_maintenance[indexPath.row]" or this (blank cells) when I use '?' instead of '!'.
I know why I don't get the nil while unwrapping error when using the '?'. But the real problem is why I am not being able to interact with the views in each of the cells to display the desired data. I have checked all the outlets, and they are all correct.
Any help would be greatly appreciated.
Thanks in advance.
Without having access to the entire project is difficult to say why it's not working.
But I think the approach you are following is not correct, you should look into having only two sections (Maintenance, Cleaning) and then each item of Maintenance and Cleaning would be a cell, so your datasource should return 2 sections and 10 rows for each section.
You would need a section header, which would have an image view, and then only one prototype cell, that you can reuse for any row.
Hope this helps.

Get section header cell in gesture method

I am working on a 'UITableView' with different section headers. Section header contains a tab gesture recognization to expand and collapse the section.
In the section header view, I have used an image for the accessory icon to show the user the section is expanded or collapsed.
My concern is when I tap section header then control goes to the gesture method. In that method how should I get the header cell to update the image accordingly?
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
if self.useSearchDefinitions {
if let ret = tableView.dequeueReusableCell(withIdentifier: INBOX_HEADER_CELL_IDENTIFIER) as? InboxHeaderCell {
ret.contentView.backgroundColor = UIColor(red: 236 / 255.0, green: 236 / 255.0, blue: 236 / 255.0, alpha: 1.0)
ret.contentView.tag = section
ret.lblHeaderTitle?.textColor = UIColor(red: 110 / 255.0, green: 110 / 255.0, blue: 110 / 255.0, alpha: 1.0)
ret.lblHeaderTitle?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
ret.lblHeaderTitle?.text = presenter.sectionTitle(section)
ret.accessoryImage.image = UIImage(named: "inbox-expand.png")
// Set tap gesture
let headerViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.headerViewGestureHandler))
headerViewTapRecognizer.delegate = self
headerViewTapRecognizer.numberOfTouchesRequired = 1
headerViewTapRecognizer.numberOfTapsRequired = 1
ret.contentView.addGestureRecognizer(headerViewTapRecognizer)
return ret.contentView
}
}
return nil
}
and this is to get the gesture
func headerViewGestureHandler(_ sender: UIGestureRecognizer)
{
tableView.beginUpdates()
if let tag = sender.view?.tag {
let section = Int(tag)
let shouldCollapse: Bool = !collapsedSections.contains((section))
let numOfRows = Int(presenter.numberOfRows(tag))
}
}
how should I get the particular clicked section header cell in this method so I can update the image accordingly?
Thanks in advance.
I would recommend:
put the Gesture code inside your section header
using a "call back" closure for passing the tap back to the view controller
Here is a simple example (assumes you have a View Controller with a Table View, hooked up via IBOutlet):
class SimpleSectionHeaderView: UITableViewHeaderFooterView, UIGestureRecognizerDelegate {
// typical UILabel
var lblHeaderTitle: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
// this is our "call back" closure
var headerTapCallback: (() -> ())?
func headerViewGestureHandler(_ sender: UIGestureRecognizer) {
// just for debugging, so we know the tap was triggered
print("tapped!!!")
// "call back" to the view controller
headerTapCallback?()
}
func commonInit() {
// set our backgroundColor
contentView.backgroundColor = .cyan
// add a label and set its constraints
self.addSubview(lblHeaderTitle)
lblHeaderTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8.0).isActive = true
lblHeaderTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
// Set tap gesture
let headerViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.headerViewGestureHandler))
headerViewTapRecognizer.delegate = self
headerViewTapRecognizer.numberOfTouchesRequired = 1
headerViewTapRecognizer.numberOfTapsRequired = 1
// add it to self
self.addGestureRecognizer(headerViewTapRecognizer)
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
}
class TableWithSectionHeadersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var theTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// standard cell registration
theTableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
theTableView.register(SimpleSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "simpleHeaderView")
// make sure these are set (in case we forgot in storyboard)
theTableView.delegate = self
theTableView.dataSource = self
}
func handleHeaderTap(_ section: Int) -> Void {
// do whatever we want based on which section header was tapped
print("View Controller received a \"tapped\" in header for section:", section)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = tableView.dequeueReusableHeaderFooterView(withIdentifier: "simpleHeaderView") as! SimpleSectionHeaderView
// set the view's label text
v.lblHeaderTitle.text = "Section \(section)"
// set the view's "call back" closure
v.headerTapCallback = {
_ in
self.handleHeaderTap(section)
}
return v
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60;
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
cell.textLabel?.text = "\(indexPath)"
return cell
}
}
This also eliminates any need to set any .tag properties (which is generally a bad idea, for a number of reasons).

iOS8 Swift - Table View - Controller does not conform to protocol UITableViewDataSource

I added another model to my database, and I am essentially re-creating the same methods for this model as the previous one, however this time around I am getting the following error:
ContactsDetailViewController.swift:11:1: Type 'ContactsDetailViewController' does not conform to protocol 'UITableViewDataSource'
EDIT: I'm also getting these errors, but again, I don't see where the issue is:
/Volumes/BigMan/Code/Swift/BackpackerSpots/UIKit.UITableViewDataSource:3:48: Protocol requires function 'tableView(_:cellForRowAtIndexPath:)' with type '(UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell'
/Volumes/BigMan/Code/Swift/BackpackerSpots/BackpackerSpots/ContactsDetailViewController.swift:14:19: Candidate is not a function
Here is my ContactsDetailViewController:
import UIKit
class ContactsDetailViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
#IBOutlet var tableView:UITableView!
var contact:Contact?
override func viewDidLoad() {
super.viewDidLoad()
// customizing background of tableview
self.tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2)
// remove extra separators
self.tableView.tableFooterView = UIView(frame: CGRectZero)
// change the color of the separator
self.tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
// self-sizing cells
tableView.estimatedRowHeight = 36.0
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int)
-> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:
NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as ContactsDetailTableViewCell
// make cell transparent so background color can be seen
cell.backgroundColor = UIColor.clearColor()
switch indexPath.row {
case 0:
cell.fieldLabel.text = "Name"
cell.valueLabel.text = contact?.contactName
case 1:
cell.fieldLabel.text = "Email"
cell.valueLabel.text = contact?.contactEmail
cell.mapButton.hidden = false
default:
cell.fieldLabel.text = ""
cell.valueLabel.text = ""
}
return cell
}
}
Here is the ContactsDetailTableViewCell:
import UIKit
class ContactsDetailTableViewCell: UITableViewCell {
#IBOutlet weak var fieldLabel:UILabel!
#IBOutlet weak var valueLabel: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
}
}
I must be overlooking something relatively simple, but I just don't see it and I've been struggling with this for hours. Any suggestions would be much appreciated. Thank you.
The are few things in the above code I would like to point out.
In cellForRowAtIndexPath method, you are using the cell identifier as "Cell", make sure you are using the same name in Storyboard and its unique across the project.
In cellForRowAtIndexPath method, brackets are not rightly marked
Try writing the following line for your cell:
let cell : ContactsDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("ContactsDetailTableViewCell", forIndexPath: indexPath) as ContactsDetailTableViewCell
Note: Make sure you rename identifier in the storyboard too.
I think you should add override:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}

Receiving nil for UIElements inside tableViewCell added via storyboard

I have created a TableViewCell entirely in storyboard just as I have in any other app. I want to set the properties however the components inside of it (such as cellScrollView) are returning nil. They are connected via IBOutlet. I have never had this happen to me before, the line where is error occurs is :
cell.cellScrollView.contentSize = CGSizeMake((2 * cell.frame.size.width), cell.frame.size.height)
And the error is:
fatal error: unexpectedly found nil while unwrapping an Optional value
Below is the ViewController..
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet weak var scrollView: UIScrollView!
func random() -> CGFloat { return CGFloat(rand()) / CGFloat(RAND_MAX) }
func randomColor() -> UIColor { return UIColor(red: random(), green: random(), blue: random(), alpha: 1.0) }
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.height)
scrollView.contentOffset = CGPoint(x: self.view.frame.size.width, y: 0)
var tableView = UITableView(frame: CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height))
tableView.dataSource = self
tableView.registerClass(SnapchatTableViewCell.self, forCellReuseIdentifier: "cell")
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
scrollView.addSubview(tableView)
// 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.
}
//TableView DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 80
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as SnapchatTableViewCell
cell.delegate = self
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.cellScrollView.contentSize = CGSizeMake((2 * cell.frame.size.width), cell.frame.size.height) //This is where the crash occurs, the error tells me cell.cellScrollView is nil
return cell
}
}
..and here is the class that inherits UITableViewCell and is the custom class of the cell in storyboard:
import UIKit
class SnapchatTableViewCell: UITableViewCell, UIScrollViewDelegate {
#IBOutlet var cellScrollView: UIScrollView!
#IBOutlet var colorView: UIView!
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
}
//ScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
}
}
Use the viewWithTag() function in the storyboard instead of using outlets.
Give your cellScrollView a tag for example of 100 then simply call cell.viewWithTag(100) as UIScrollView to access your scroll view. Do the same for all subviews in your cell.

Resources