logo
down
shadow

Troubleshooting Custom UITableView Cell [Swift]


Troubleshooting Custom UITableView Cell [Swift]

By : Shaun Hare
Date : November 22 2020, 01:01 AM
I think the issue was by ths following , The debugger output shows that cell is nil, meaning it could not be instantiated. Furthermore, you are forcing an unwrapping of the optional (using the !) which causes the app to crash on the nil value.
Try to change your cellForRowAtIndexPath method like so (notice the dequeueReusableCellWithIdentifier method):
code :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as StatusCell

    cell.InstrumentType.text = Items[indexPath.row]
    cell.InstrumentValue.text = "150 Km"
    cell.InstrumentImage.image = UIImage(named: Items[indexPath.row])

    return cell
}


Share : facebook icon twitter icon
How to load Custom cell (Xib) in UITableview using Swift

How to load Custom cell (Xib) in UITableview using Swift


By : user3157472
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Here's my code
code :
import UIKit
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //MARK:- Sample Data Array to load in TableView
        let sampleArrray: \[String\] = \["val1", "val2", "val3", "val4", "val5"]

    //MARK:- Cell reuse identifier 
        let cellReuseIdentifier = "cell"


    //MARK:- UITableView outlet 
         @IBOutlet var tableView: UITableView!

          override func viewDidLoad() {
            super.viewDidLoad()

            // Registering the custom cell

            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

            // Setting delegate and Datasourse as same viewcontroller (this code is not neccessory if we are setting it from storyboard)

            tableView.delegate = self
            tableView.dataSource = self
        }
    //UITableview required methods 

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return sampleArrray.count
        }

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

            cell.textLabel?.text = sampleArrray\[indexPath.row\]

            return cell
        }

        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
           print("clicked at: \(indexPath.row)")
           //Here u can get the selected cell and add action related to this cell seelction 
        }
Swift UItableView Custom cell programmatically (documentation)?

Swift UItableView Custom cell programmatically (documentation)?


By : Ali Parsai
Date : March 29 2020, 07:55 AM
Any of those help I just played little bit. Even though all the colors/fonts are not quite right, this will give you good starting point. Hope it helps you.
code :
class Stock {
var name: String?
var action: String?
var price: String?
init(stockData: [String: AnyObject]) {
    if let n = stockData["stockName"] as? String {
        name = n
    }
    if let a = stockData["action"] as? String {
        action = a
    }
    if let p = stockData["stockPrice"] as? Float {
        price = NSString(format: "%.2f", p)
    }
}

var backgroundColor: UIColor {
    if action == "sell" {
        return UIColor.greenColor()
    }
    return UIColor.blueColor()
}

var typeColor: UIColor {
    if action == "sell" {
        return UIColor.blackColor()
    }
    return UIColor.purpleColor()
}

var priceLabelColor: UIColor {
    if action == "sell" {
        return UIColor.redColor()
    }
    return UIColor.greenColor()
}
}


class StockCell: UITableViewCell {

let padding: CGFloat = 5
var background: UIView!
var typeLabel: UILabel!
var nameLabel: UILabel!
var priceLabel: UILabel!

var stock: Stock? {
    didSet {
        if let s = stock {
            background.backgroundColor = s.backgroundColor
            priceLabel.text = s.price
            priceLabel.backgroundColor = s.priceLabelColor
            typeLabel.text = s.action
            typeLabel.backgroundColor = s.typeColor
            nameLabel.text = s.name
            setNeedsLayout()
        }
    }
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    backgroundColor = UIColor.clearColor()
    selectionStyle = .None

    background = UIView(frame: CGRectZero)
    background.alpha = 0.6
    contentView.addSubview(background)

    nameLabel = UILabel(frame: CGRectZero)
    nameLabel.textAlignment = .Left
    nameLabel.textColor = UIColor.blackColor()
    contentView.addSubview(nameLabel)

    typeLabel = UILabel(frame: CGRectZero)
    typeLabel.textAlignment = .Center
    typeLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(typeLabel)

    priceLabel = UILabel(frame: CGRectZero)
    priceLabel.textAlignment = .Center
    priceLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(priceLabel)
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func prepareForReuse() {
    super.prepareForReuse()

}

override func layoutSubviews() {
    super.layoutSubviews()
    background.frame = CGRectMake(0, padding, frame.width, frame.height - 2 * padding)
    typeLabel.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
    priceLabel.frame = CGRectMake(frame.width - 100, padding, 100, frame.height - 2 * padding)
    nameLabel.frame = CGRectMake(CGRectGetMaxX(typeLabel.frame) + 10, 0, frame.width - priceLabel.frame.width - (CGRectGetMaxX(typeLabel.frame) + 10), frame.height)
}
}
var stocks: [Stock] = []

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.whiteColor()

    for stockData in dataArray {
        var stock = Stock(stockData: stockData)
        stocks.append(stock)
    }


    tableView = UITableView(frame: view.bounds, style: .Grouped)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .None
    tableView.registerClass(StockCell.self, forCellReuseIdentifier: NSStringFromClass(StockCell))
    view.addSubview(tableView)
}



func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stocks.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier( NSStringFromClass(StockCell), forIndexPath: indexPath) as StockCell
    cell.stock = stocks[indexPath.row]
    return cell

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 70
}
class StockCell: UITableViewCell {

let padding: CGFloat = 5
var background: UIView!
var typeLabel: UILabel!
var nameLabel: UILabel!
var priceLabel: UILabel!

var stock: Stock? {
    didSet {
        if let s = stock {
            background.backgroundColor = s.backgroundColor
            priceLabel.text = s.price
            priceLabel.backgroundColor = s.priceLabelColor
            typeLabel.text = s.action
            typeLabel.backgroundColor = s.typeColor
            nameLabel.text = s.name
            setNeedsLayout()
        }
    }
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    backgroundColor = UIColor.clearColor()
    selectionStyle = .None

    background = UIView(frame: CGRectZero)
    background.alpha = 0.6
    contentView.addSubview(background)

    nameLabel = UILabel(frame: CGRectZero)
    nameLabel.textAlignment = .Left
    nameLabel.textColor = UIColor.blackColor()
    contentView.addSubview(nameLabel)

    typeLabel = UILabel(frame: CGRectZero)
    typeLabel.textAlignment = .Center
    typeLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(typeLabel)

    priceLabel = UILabel(frame: CGRectZero)
    priceLabel.textAlignment = .Center
    priceLabel.textColor = UIColor.whiteColor()
    contentView.addSubview(priceLabel)
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func prepareForReuse() {
    super.prepareForReuse()

}

override func layoutSubviews() {
    super.layoutSubviews()
    background.frame = CGRectMake(0, padding, frame.width, frame.height - 2 * padding)
    typeLabel.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
    priceLabel.frame = CGRectMake(frame.width - 100, padding, 100, frame.height - 2 * padding)
    nameLabel.frame = CGRectMake(CGRectGetMaxX(typeLabel.frame) + 10, 0, frame.width - priceLabel.frame.width - (CGRectGetMaxX(typeLabel.frame) + 10), frame.height)
}
}
Swift: How to get the value of a slider in a custom cell in a dynamic UITableView?

Swift: How to get the value of a slider in a custom cell in a dynamic UITableView?


By : Jade
Date : March 29 2020, 07:55 AM
Does that help I have a problem with the following scenario: , Try adding this to your cellForRowAtIndexPath function:
code :
cell.cellSlider.tag = indexPath.row
cell.cellSlider.addTarget(self, action: "sliderValueChange:", forControlEvents: .ValueChanged)
func sliderValueChange(sender: UISlider) {
    // Get the sliders value
    var currentValue = Int(sender.value)
    var sliderRow = sender.tag

    // Do whatever you want with the value :)
    // And now the row of the slider!
}
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2    // 2 rows in the cell, for demo purposes
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

        cell.slider.tag = indexPath.row
        cell.slider.addTarget(self, action: "sliderChange:", forControlEvents: .ValueChanged)

        return UITableViewCell()
    }

    func sliderChange(sender: UISlider) {
        let currentValue = sender.value    // get slider's value
        let row = sender.tag               // get slider's row in table

        print("Slider in row \(row) has a value of \(currentValue)")
        // example output - Slider in row 1 has a value of 0.601399
    }

}

class TableViewCell: UITableViewCell {

    @IBOutlet var slider: UISlider!

}
UITableView always displays basic cell instead of custom cell in Swift

UITableView always displays basic cell instead of custom cell in Swift


By : user7742088
Date : March 29 2020, 07:55 AM
Hope this helps You are creating your custom cell directly on the tableview in the storyboard, right ? If this is the case then you don't need to register the cell in your viewDidLoad as the storyboard takes care of that. You just deque it and it's good to go.
If you register it manually you just override what the storyboard did and end up getting a regular cell as the cell gets instantiated from the code instead of getting instantiated from the storyboard.
How to load array value int cell without creating multiple custom cell in UITableView iOS Swift?

How to load array value int cell without creating multiple custom cell in UITableView iOS Swift?


By : lwfshensi
Date : March 29 2020, 07:55 AM
Does that help @Parameswaran V
Here below check my simple updated answer for Can you suggest me best way for above one while passing json
code :
    struct DemoItems {

        var key: String?
        var value: String?
    }

fileprivate var demoItems: [DemoItems]?

fileprivate func loadDemoItems() -> [DemoItems] {

        var tempItems = [DemoItems]()

        let item1 = DemoItems.init(key: "Material#", value: "")
        let item2 = DemoItems.init(key: "Description", value: "Bottles")
        let item3 = DemoItems.init(key: "Fixed Vendor#", value: "KP04")
        let item4 = DemoItems.init(key: "Vendor Name", value: "KP Suppliers")
        let item5 = DemoItems.init(key: "Purch Org", value: "1000")

        tempItems.append(item1)
        tempItems.append(item2)
        tempItems.append(item3)
        tempItems.append(item4)
        tempItems.append(item5)

        return tempItems
    }
    demoItems = loadDemoItems()

    if let tempDemoItems = demoItems {

        print(tempDemoItems)
        print(tempDemoItems[0].key)
        print(tempDemoItems[0].value)
    }
[permisdesauver_dev.DemoItems(key: Optional("Material#"), value: Optional("")), permisdesauver_dev.DemoItems(key: Optional("Description"), value: Optional("Bottles")), permisdesauver_dev.DemoItems(key: Optional("Fixed Vendor#"), value: Optional("KP04")), permisdesauver_dev.DemoItems(key: Optional("Vendor Name"), value: Optional("KP Suppliers")), permisdesauver_dev.DemoItems(key: Optional("Purch Org"), value: Optional("1000"))]
Optional("Material#")
Optional("")
Related Posts Related Posts :
  • Unclear about releasing CFDictionaryRef
  • CordovaError: Promise rejected with non-error: Error code 65
  • How to append NSMutable strings into a UILabel
  • CustomCell label value does not change
  • Display ad in iAd Bannerview iAd Network
  • Warning: "Could not get traitsetID for iPhone11,6" (Assets.xcassets)
  • Changing root view controller after iOS app has loaded.
  • SocketRocket and iOS certificate pinning
  • Draggable UIButton Snap To a Circle Path
  • Running FireBase in the background
  • resizing UIPopoverController to fit UITableController
  • UICollectionView Exception Crash
  • targeting iOS5 - will it work on iOS6 also?
  • FBLoginView get email
  • Scale UIImages height to UIImageView height
  • Creating a custom progress indicator in ios
  • NSRunLoop API difference
  • Is it possible to inject custom settings into my iOS application "Notifications" settings dialog?
  • UIAlertview not accepting string as message
  • Axis change of stackView giving layout error
  • How to use AVAssetResourceLoader?
  • How to write block definition using properties?
  • iOS connect/reconnect to Bluetooth device when using external-accessory and MFi
  • Saving XMPP Multi User chat messages through XMPP MessageArchiving in iOS
  • Deciding iOS version: pros and cons
  • iOS: Resigned app cannot access keychain through security API
  • How can I set To and Subject fields in an E-Mail being sent by UIDocumentInteractionController?
  • Updating uilabel in view controller underneath another
  • Maximum time Intervel for NSTimer
  • Delete Core Data Entry from Table View Controller
  • How to unload UIViewcontroller from memory?
  • Compressing UIImage as Far as Possible?
  • Optimizing workflow to update internally owned cocoapods dependencies?
  • Formatting an NSDate with Abbreviated Month/Day Names
  • I'm creating a quiz game with 4 answers and I want to add score
  • Tap Gesture to Hide Navigation Bar, Tab Bar, and Status Bar
  • FBSessionStateClosedLoginFailed when I am logged in through Settings
  • CGRect positioning according to center point
  • iOS: Update table view datasource with animations without core data
  • iOS : Where to start for AliPay integration?
  • Routing App Coverage File missing but not needed?
  • Drawing on a zoomable view
  • Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary
  • Terminating app due to uncaught exception 'NSRangeException' when calling dequeueReusableCellWithReuseIdentifier:forInde
  • Collision without physics (Cocos2D + Box2D iOS)
  • Creating a percentage based iOS layout
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org