Swift - Increment Label with Stepper in TableView Cell - swift

Another Swift beginner here. I simply want a Stepper in each of my TableView cells that increments a label in the same cell.
I have found a couple of questions on this topic, but they include other elements and I haven't been able to extract the basic concept.
Swift Stepper Action that changes UITextField and UILabel within same cell
Stepper on tableview cell (swift)
So far I have connected IBOutlets for my Label and Stepper, as well as an IBAction for my Stepper in my cell class.
class BuyStatsCell: UITableViewCell{
//these are working fine
#IBOutlet weak var category: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var price: UILabel!
//Outlet for Label and Stepper - How do I make these work?
#IBOutlet weak var purchaseAmount: UILabel!
#IBOutlet weak var addSubtract: UIStepper!
//Action for Stepper - And this?
#IBAction func stepperAction(_ sender: UIStepper) {
self.purchaseAmount.text = Int(sender.value).description
}
}
And I understand the concept of reusing the cell in the cellForRowAt indexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BuyStatsTabCell", for: indexPath) as! BuyStatsCell
cell.isUserInteractionEnabled = false
//these are working
cell.category.text = categories[indexPath.row]
cell.price.text = String(prices[indexPath.row])
cell.average.text = String(averages[indexPath.row])
//but is there something I need to add here to keep the correct Stepper and Label for each class?
return cell
}
One of the already asked questions includes a protocol and another function in the ViewController like this
protocol ReviewCellDelegate{
func stepperButton(sender: ReviewTableViewCell)
}
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
}
}
I don't know if this is the approach I should be trying to take. I am looking for the simplest solution, but I am having trouble putting the pieces together.
Any help is appreciated.
Thanks.

Easiest solution (simplyfied):
Create a model BuyStat with a property purchaseAmount (it's crucial to be a class).
You are strongly discouraged from using multiple arrays as data source
class BuyStat {
var purchaseAmount = 0.0
init(purchaseAmount : Double) {
self.purchaseAmount = purchaseAmount
}
}
In the view controller create a data source array
var stats = [BuyStat]()
In viewDidLoad create a few instances and reload the table view
stats = [BuyStat(purchaseAmount: 12.0), BuyStat(purchaseAmount: 20.0)]
tableView.reloadData()
In the custom cell create a property buyStat to hold the current data source item with an observer to update stepper and label when buyStat is set
class BuyStatsCell: UITableViewCell {
#IBOutlet weak var purchaseAmount: UILabel!
#IBOutlet weak var addSubtract: UIStepper!
var buyStat : BuyStat! {
didSet {
addSubtract.value = buyStat.purchaseAmount
purchaseAmount.text = String(buyStat.purchaseAmount)
}
}
#IBAction func stepperAction(_ sender: UIStepper) {
buyStat.purchaseAmount = sender.value
self.purchaseAmount.text = String(sender.value)
}
}
In cellForRowAtIndexPath get the data source item and pass it to the cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BuyStatsTabCell", for: indexPath) as! BuyStatsCell
cell.buyStat = stats[indexPath.row]
return cell
}
The magic is: When you are tapping the stepper the label as well as the data source array will be updated. So even after scrolling the cell will get always the actual data.
With this way you don't need protocols or callback closures. It's only important that the model is a class to have reference type semantics.

NOTE: MY Cell class is just normal..All changes are in viewcontroller class
class cell: UITableViewCell {
#IBOutlet weak var ibAddButton: UIButton!
#IBOutlet weak var ibStepper: UIStepper!
#IBOutlet weak var ibCount: UILabel!
#IBOutlet weak var ibLbl: UILabel!
}
1.define empty int array [Int]()
var countArray = [Int]()
2.append countArray with all zeros with the number of data u want to populate in tableview
for arr in self.responseArray{
self.countArray.append(0)
}
3.in cell for row at
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell
let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary()
cell.ibLbl.text = dict["name"] as? String ?? String()
if countArray[indexPath.row] == 0{
cell.ibAddButton.tag = indexPath.row
cell.ibStepper.isHidden = true
cell.ibAddButton.isHidden = false
cell.ibCount.isHidden = true
cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside)
}else{
cell.ibAddButton.isHidden = true
cell.ibStepper.isHidden = false
cell.ibStepper.tag = indexPath.row
cell.ibCount.isHidden = false
cell.ibCount.text = "\(countArray[indexPath.row])"
cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)}
return cell
}
4.objc functions
#objc func stepperValueChanged(sender : UIStepper){
if sender.stepValue != 0{
countArray[sender.tag] = Int(sender.value)
}
ibTableView.reloadData()
}
#objc func addPressed(sender : UIButton){
countArray[sender.tag] = 1//countArray[sender.tag] + 1
ibTableView.reloadData()
}

Related

Swift UITableViewCell not showing Labels

I'm trying to create a custom cell view with some labels, I have created a subclass of UITableViewCell and connected the labels to it. Inside cellForRowAt method I dequeued the cell and cast it as YourCell subclass to access the labels and set text.
Setting class of cell to YourCell
However when running the app, nothing is showing up.
class YourCell: UITableViewCell {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
let array1 = ["Name1", "Name2","Name3","Name3"]
let array2 = ["1","2","3","4"]
let array3 = ["18","17","11","9"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! YourCell
cell.label1.text = array1[indexPath.row]
cell.label2.text = array2[indexPath.row]
cell.label3.text = array3[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array2.count
}
}
You have conformed the UITableViewDelegate protocol correctly, the only thing you are missing is to set up your datasource by including this line in your viewDidLoad.
tableview.dataSource = self

How to assign the specific endpoint to the specific selected cell

I have some data coming from the API and I am showing them in tableView cells, Each of those cell's have a "Download" button, I need to assign a fileID from API to the cell that the user has selected to Download.
I have already set up the button to a UITableViewCell class, I just need to have a idea how to make the button get the fileID depending on which cell is clicked since every cell has it's own fileID.
paymentsViewController class:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "paymentsCell", for: indexPath) as? paymentsModel else {return UITableViewCell()}
let currentInvoice = payments.Result![changeCustomerKey.DefaultsKeys.keyTwo].properties?[0].payments
let currentInvoices = currentInvoice?[indexPath.row]
cell.priceLabelPayments?.text = "€\(currentInvoices?.amount ?? 0.00)"
cell.whenDateLabel?.text = "\(currentInvoices?.insertionDate?.convertToDisplayForm() ?? "")"
cell.fromSubLabel.text = "\(currentInvoices?.bank ?? "")"
cell.downloadButtonPayments.layer.cornerRadius = CGFloat(5)
cell.localizePaymentsModel()
return cell
}
}
paymentsModel class:
class paymentsModel: UITableViewCell {
#IBOutlet weak var cellContentViewPayments: UIView!
#IBOutlet weak var downloadButtonPayments: UIButton!
#IBOutlet weak var priceLabelPayments: UILabel!
#IBOutlet weak var fromSubLabel: UILabel!
#IBOutlet weak var whenDateLabel: UILabel!
func localizePaymentsModel() {
let defaults = UserDefaults.standard
let lang = defaults.string(forKey: changeLanguageKey.DefaultsKeys.keyOne)
downloadButtonPayments.setTitle(NSLocalizedString("Download", tableName: nil, bundle: changeLanguage.createBundlePath(lang: lang ?? "sq" ), value: "", comment: ""), for: UIControl.State.normal)
}
}
You are thinking about this wrong. It isn't the cell that has the fileID. When the user taps on a cell or a button, you should ask the table view (or collection view) for the indexPath it currently occupies, then use the IndexPath to look up the model data for that entry.
See my answer here:
Thant link shows code that lets you figure out the IndexPath for any view in a table view cell. You could use that code from your button's IBAction.

Connect UITableviewCell with UITableview using Combine repeat values

I'm learning combine and I want to use combine instead a delegate between cell and tableview. I have managed to connect and receive the information, but the problem is when the cell is reused, every time I generate the same event, I receive it as many times as it has been used previously in that reused cell.
I have declared cancelables in the view controller as
var cancellables: Set<AnyCancellable> = []
And this is the cellForRow method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.celdaReuseIdentifier, for: indexPath)
as? MyCell else {
return MyCell()
}
cell.index = indexPath
cell.lbTitle.text = String("Cell \(indexPath.row)")
cell.tapButton.compactMap{$0}
.sink { index in
print("tap button in cell \(index.row)")
}.store(in: &cancellables)
return cell
}
and the cell is
class MyCell: UITableViewCell {
static let cellNibName = "MyCell"
static let celdaReuseIdentifier = "MyCellReuseIdentifier"
#IBOutlet weak var lbTitle: UILabel!
#IBOutlet weak var button: UIButton!
var index: IndexPath?
let tapButton = PassthroughSubject<IndexPath?, Never>()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBAction func tapButton(_ sender: Any) {
self.tapButton.send(index)
}
}
Thanks for your help
To solve your problem with reused cells you must add the Set<AnyCancellable> to the cell.
If you are only going to use an event inside cells you can use a single AnyCancellable:
Single Event (AnyCancellable)
Declares a variable in the cell of AnyCancellable Type. Every time the cell is reused a new publisher will be added replacing the previous one and you will not receive the event multiple times.
Cell
class MyCell: UITableViewCell {
static let cellNibName = "MyCell"
static let celdaReuseIdentifier = "MyCellReuseIdentifier"
#IBOutlet weak var lbTitle: UILabel!
#IBOutlet weak var button: UIButton!
var index: IndexPath?
// store publisher here
var cancellable: AnyCancellable?
// Single Publisher per cell
let tapButton = PassthroughSubject<IndexPath?, Never>()
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func tapButton(_ sender: Any) {
self.tapButton.send(index)
}
}
ViewController
In the Viewcontroller you just have to add the publisher to the cancellable.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.celdaReuseIdentifier, for: indexPath)
as? MyCell else {
return MyCell()
}
cell.index = indexPath
cell.lbTitle.text = String("Cell \(indexPath.row)")
// Add your publisher to your cancellable and remove store function.
cell.cancellable = cell.tapButton.compactMap{$0} .sink { index in
print("tap button in cell \(index.row)")
}
return cell
}
Multiples events (Set<AnyCancellable>)
Here it is the same but using a collection in case you want to have more events than just one.
Cell
Create a variable Set<AnyCancellable> to store the publishers.
In this case, before reusing the cell, we will have to remove the cancellables before creating new ones.
class MyCell: UITableViewCell {
static let cellNibName = "MyCell"
static let celdaReuseIdentifier = "MyCellReuseIdentifier"
#IBOutlet weak var lbTitle: UILabel!
#IBOutlet weak var button: UIButton!
var cancellables: Set<AnyCancellable>?
var index: IndexPath?
// Multiple Publishers per cell
let tapButton = PassthroughSubject<IndexPath?, Never>()
let tapView = PassthroughSubject<UIImage, Never>()
// Remove all suscriptions before reuse cell
override func prepareForReuse() {
super.prepareForReuse()
cancellables.removeAll()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBAction func tapButton(_ sender: Any) {
self.tapButton.send(index)
}
}
ViewController
In the Viewcontroller you just have to store the publishers.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.celdaReuseIdentifier, for: indexPath)
as? MyCell else {
return MyCell()
}
cell.index = indexPath
cell.lbTitle.text = String("Cell \(indexPath.row)")
// Add your publisher to your cell´s collection of AnyCancellable
cell.tapButton.compactMap{$0}
.sink { index in
print("tap button in cell \(index.row)")
}.store(in: &cell.cancellables)
return cell
}
Good Luck!! 😉
You have analyzed and described the problem perfectly. And so the cause is clear. Look at your cellForRow implementation and think about what it does: You are creating and adding a new pipeline to your cancellables every time your cellForRow runs, regardless of whether you've already added a pipeline for this instantiation of the cell.
So you need a way not to do that. Can you think of a way? Hint: attach the pipeline to the cell and vend it from there, so there is only one per cell. Your Set won't add the same pipeline twice, because it is a Set.

Configure in TableView is not being reached

So I am trying to have a TableView displayed, but I'm currently only getting an empty tableview. Upon further inspection, I see that the configure block is not being run. Why is this?
Code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: teamCellIdentifier, for: indexPath)
print("reached")
func configure(cell: UITableViewCell,
for indexPath: IndexPath) {
print("not reached")
guard let cell = cell as? TeamCell else {
return
}
let team = fetchedResultsController.object(at: indexPath)
cell.teamLabel.text = team.teamName
cell.scoreLabel.text = "Wins: \(team.wins)"
if let imageName = team.imageName {
cell.flagImageView.image = UIImage(named: imageName)
} else {
cell.flagImageView.image = nil
}
}
return cell
}
}
TeamCell
class TeamCell: UITableViewCell {
// MARK: - IBOutlets
#IBOutlet weak var teamLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var flagImageView: UIImageView!
// MARK: - View Life Cycle
override func prepareForReuse() {
super.prepareForReuse()
teamLabel.text = nil
scoreLabel.text = nil
flagImageView.image = nil
}
}
The reason why your tableView is empty or it looks like empty and your tableView methods are not being called are two reasons.
1)- Table view heigh or width is equal to 0 and there is no need to load and display tableView, respectively tableView cell.
2)- You did not connect tableView data source and delegates to your view controller.
2.1) You can add TableView delegates and data sources through storyboard (see image down below)
2.2) You can add TableView delegates and data sources thrugh code in your view controller, like:
2.2.1) In viewDidLoad() method:
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// TableView Delegates & DataSource
tableView.delegate = self
tableView.dataSource = self
}
2.2.2) Or view tableView outlet didSet (I prefer this way, if I don't do it via storyboard):
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
Your code has a structure like this:
// This next line defines a function called a
func a() {
print("a")
// This next line only defines a function called b:
// that is scoped inside the 'a' function
func b() {
print("b")
}
// Defining a function does not invoke the function
// That would need an actual call here like this:
// b()
}
// I can't call b here because it's nested inside the function 'a'
First you have a nested func inside function?
Take it out....
then after this line :
let cell = tableView.dequeueReusableCell(withIdentifier: teamCellIdentifier, for: indexPath)
do this:
configure(cell: cell,for indexPath: indexPath)

Swift, preventing tableview cell resueable

How to solve the table view data overlapped issue?
I have searched some Object C version answer, but it seems not working for Swift. I tried to get cell==nil, but it gives me an error
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let current_patient = patients[indexPath.row]
let cell = myTable.cellForRowAtIndexPath(indexPath) as! PatientTableViewCell
if (cell){
let cell = myTable.dequeueReusableCellWithIdentifier("patientCell") as! PatientTableViewCell
}
let cell = myTable.dequeueReusableCellWithIdentifier("patientCell", forIndexPath: indexPath) as! PatientTableViewCell
if(cell != nil){
var subviews = cell.contentView.subviews
subviews.removeAll()
}
//configure cell
let type = current_patient.enrollable_type
cell.patientTypelbl.text = type
return cell
}
After two-days struggling, I figure it out finally. The key to solve it is to find which cell is been resued. What I am doing now is give a var identifier to cell.
class PatientTableViewCell: UITableViewCell {
#IBOutlet weak var followupBtn: UIButton!
#IBOutlet weak var viewBtn: UIButton!
#IBOutlet weak var titleType: UILabel!
#IBOutlet weak var titleID: UILabel!
#IBOutlet weak var patientTypelbl: UILabel!
#IBOutlet weak var patientIDlbl: UILabel!
**var identifier = false**
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let current_patient = patients[indexPath.row]
var cell = myTable.dequeueReusableCellWithIdentifier("patientCell") as! PatientTableViewCell
if(cell.identifier == true){
cell = myTable.dequeueReusableCellWithIdentifier("patientCell") as! PatientTableViewCell
}
//config cell
cell.identifier = true //important
I hope it can help someone else. :)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let current_patient = patients[indexPath.row]
let cell: PatientTableViewCell! = tableView.dequeueReusableCellWithIdentifier("patientCell") as? PatientTableViewCell
//configure cell
let type = current_patient.enrollable_type
cell.patientTypelbl.text = type
return cell
}