If someone taps over the cell or selects the cell then the button will show or else it'll be hidden. Only that cell that is playing the current song will show the button (it's for either play or stop) but the problem is the button shown on each row of the cell if didn't hide it also I don't want to hide the button if I click the playing song cell again.
class AudioListViewController: UIViewController {
var selectedRowIndex = -1
var songList: [Audio] = [
Audio(id: 0, trackName: "Song 1", trackTitle: "ABbcd:", album: "Loreim loreim",
uploadedBy: "A men", genre: "Romantic", lyricsLang: "English", artist: "God",
duration: 2.00),
Audio(id: 1, trackName: "Song 2", trackTitle: "ABbcd:", album: "Loreim loreim",
uploadedBy: "A men", genre: "Romantic", lyricsLang: "English", artist: "God",
duration: 2.00),
Audio(id: 2, trackName: "Song 3", trackTitle: "ABbcd:", album: "Loreim loreim",
uploadedBy: "A men", genre: "Romantic", lyricsLang: "English", artist: "God",
duration: 2.00)
]
#IBOutlet weak var songListTableView: UITableView!
var isTapped: Bool = false
#IBOutlet weak var close: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
songListTableView.dataSource = self
songListTableView.delegate = self
songListTableView.register(UINib(nibName: "SongsListTableViewCell", bundle: nil),
forCellReuseIdentifier: "SongListCell")
}
}
extension AudioListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SongListCell",
for: indexPath) as! SongsListTableViewCell
cell.songTitle?.text = songList[indexPath.row].trackName
cell.songDuration?.text = String(songList[indexPath.row].duration)
return cell
}
}
extension AudioListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let position = indexPath.row
let vc = tableView.dequeueReusableCell(withIdentifier: "SongListCell",
for: indexPath) as! SongsListTableViewCell
}
}
My UITableViewCell code:
class SongsListTableViewCell: UITableViewCell {
public var position: Int = 0
public var isPlaying: Bool = false
var cellsState: Bool = false
#IBOutlet weak var singleViewCell: UIStackView!
#IBOutlet weak var songCellView: UIView!
#IBOutlet weak var songImage: UIImageView!
#IBOutlet weak var songTitle: UILabel!
#IBOutlet weak var songDuration: UILabel!
#IBOutlet weak var makeFavorite: UIButton!
#IBOutlet weak var useSong: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
useSong.addTarget(self, action: #selector(SongsListTableViewCell.selectSong(_:)), for: .touchUpInside)
makeFavorite.addTarget(self, action: #selector(SongsListTableViewCell.makeFavourite(_:)), for: .touchUpInside)
useSong.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
useSong.layer.cornerRadius = 6
}
#IBAction func makeFavourite(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
makeFavorite.setImage(UIImage(systemName: "star.fill"), for: .normal)
} else {
makeFavorite.setImage(UIImage(systemName: "star"), for: .normal)
}
}
}
This is how it's looking right now:
This is my Songlistview:
Hello Tyler i am using function in UITableViewDelegate with didSelectRowAt and didDeselectRowAt to show and hide , and don't hide why i click the component in Cell , with the function will check row in the index path and call function hide/show
import UIKit
class ShowHideTableviewVC: UIViewController {
#IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.dataSource = self
self.tableview.delegate = self
}
}
extension ShowHideTableviewVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ShowHideCell", for: indexPath) as! ShowHideCell
return cell
}
}
extension ShowHideTableviewVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ShowHideCell {
cell.showButton(show: true)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ShowHideCell {
cell.showButton(show: false)
}
}
}
and this is the code in the cell it will hide the button component and make the height zero because we want hide the button component
import UIKit
class ShowHideCell: UITableViewCell {
#IBOutlet weak var buttonx: UIButton!
#IBOutlet weak var heightButton: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
showButton(show: false)
}
func showButton(show: Bool) {
if show {
heightButton.constant = 30
buttonx.isHidden = !show
} else {
heightButton.constant = 0
buttonx.isHidden = !show
}
}
}
it will not hide the button (play button) when you click the button component inner cell because it using selected in the UITableViewDelegate
Related
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, pass {
var array = [String]()
#IBOutlet weak var tblView: UITableView!
#IBOutlet weak var btnPush: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as!TableViewCell
cell.lblName.text = array[indexPath.row]
cell.lblFullName.text = array[indexPath.row]
cell.lblRollno.text = array[indexPath.row]
cell.lblClass.text = array[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
#IBAction func btnPush(_ sender: UIButton) {
let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as!SecondVC
vc.mac = self
self.navigationController?.pushViewController(vc, animated: true)
}
func Datapass(Name: String, FullName Address: String, Rollno: String, Class: String) {
self.array.append(Name)
self.array.append(Address)
self.array.append(Rollno)
self.array.append(Class)
tblView.reloadData()
}
}
import UIKit
protocol pass {
func Datapass(Name:String, FullName:String, Rollno:String, Class:String)
}
class SecondVC: UIViewController {
#IBOutlet weak var textFldName: UITextField!
#IBOutlet weak var txtFldFullName: UITextField!
#IBOutlet weak var txtFldRollno: UITextField!
#IBOutlet weak var txtFldClass: UITextField!
var mac:pass?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnAdd(sender: UIButton) {
mac?.Datapass(Name: textFldName.text!, FullName: txtFldFullName.text!, Rollno: txtFldRollno.text!, Class: txtFldClass.text!)
self.navigationController?.popViewController(animated: true)
}
}
your adding data to your array the wrong way. your adding 4 parameter
and your array will be like this:
array: 0:name|1:Address|2:Rollno|3:Class
and when your reading this from table every time you map this:
cell.lblName.text = array[0]
cell.lblFullName.text = array[0]
cell.lblRollno.text = array[0]
cell.lblClass.text = array[0]
every time table only reads one element of array for 4 times! you are not changing indexpath.row , it will change it's number after loading 1 cell.
the right way to do this is code below:
struct DbModel{
var name:String
var address:String
var rollno:String
var `class`:String
}
var array :[DbModel] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
let model = array[indexPath.row]
cell.lblName.text = model.name
cell.lblFullName.text = model.address
cell.lblRollno.text = model.rollno
cell.lblClass.text = model.class
return cell
}
func Datapass(Name: String, FullName Address: String, Rollno: String, Class: String) {
let model = DbModel(name: Name, address: Address, rollno: Rollno, class: Class)
self.array.append(model)
tblView.reloadData()
}
i created table view with custom UITableViewCell class. So my app should set UIStepper hidden when button in navigation bar is tapped. Than it should update count Label by Stepper's value
My app's mission to see count and list of medicines at your home. So update each medical's count when stepper at that row is tapped.
import UIKit
class MedicinesListPage: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
struct Medicine {
var name: String
var count: Int
}
var medicines = [
Medicine(name: "Парацетамол", count: 1),
Medicine(name: "Ибуфен", count: 2),
Medicine(name: "Цитрамон", count: 1),
Medicine(name: "Смекта", count: 1),
Medicine(name: "Мезин", count: 1),
Medicine(name: "Терафлю", count: 1),
Medicine(name: "Спирт", count: 1),
Medicine(name: "Бинт", count: 1),
Medicine(name: "Мукалтин", count: 1),
Medicine(name: "Стрепсилс", count: 1)
]
override func viewDidLoad() {
super.viewDidLoad()
let rightButton = UIBarButtonItem(title: "Add", style: UIBarButtonItem.Style.plain, target: self, action:(#selector(showEditing)))
navigationItem.rightBarButtonItem = rightButton
tableView.delegate = self
tableView.dataSource = self
}
#objc func showEditing(){
// should unhide stepper
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 65
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return medicines.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "medicalTableViewCell") as? medicalTableViewCell
cell?.configureCell(name: medicines[indexPath.row].name, count: medicines[indexPath.row].count)
return cell!
}
}
UITableViewCell class
import UIKit
final class medicalTableViewCell: UITableViewCell{
#IBOutlet weak var medicalName: UILabel!
#IBOutlet weak var medicalCount: UILabel!
#IBOutlet weak var stepper: UIStepper!
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func stepperTapped(_ sender: UIStepper) {
// should update count of medicals
}
public func configureCell(name: String, count: Int){
medicalName.text = name
medicalCount.text = String(count)
}
}
As I understood, you have a TableViewController with customs UITableView cells.
Each cell contains medicine name, its number and the UIStepper (that allows to change the number of that medicine).
You goal is to update medicalCountLabel every time the UIStepper is tapped.
(from the conversation in the comments, this is what I implemented)
Custom UITableViewCell Class
import UIKit
class TableViewCell: UITableViewCell {
//MARK: - Properties
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var countLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
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
}
//MARK: - Actions
#IBAction func stepperTapped(_ sender: UIStepper) {
countLabel.text = Int(sender.value).description
} //this is where you update `medicalCountLabel`
}
TableViewController Class:
import UIKit
class TableViewController: UITableViewController {
//MARK: - Properties
var medicines = [Medicine(name: "Парацетамол", count: 4), Medicine(name: "Ибуфен", count: 7),Medicine(name: "Цитрамон", count: 4),Medicine(name: "Смекта", count: 9), Medicine(name: "Мезин", count: 2)]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return medicines.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell else{
fatalError("The dequeued cell is not an instance of TableViewCell.")
}
// Configure the cell
let medicine = medicines[indexPath.row]
cell.nameLabel.text = medicine.name
cell.countLabel.text = String(medicine.count)
cell.stepper.value = Double(medicine.count)
return cell
}
}
Medicine Class (in your case you just did it using struct which is also fine; but I created a separate swift file):
import UIKit
class Medicine{
var name: String
var count: Int
init(name: String, count: Int){
self.name = name
self.count = count
}
}
var medicalNames: [String] = ["item 1", "item 2", "item 3"]
var medicalCount: [Int] = [5,2,7]
This is bad design - make this an array of structs instead:
struct Medicine {
let name: String
var count: Int
}
let medicines = [
Medicine(name: "foo", count: 1), Medicine(name: "bar", count: 2)
]
Once you've done that, you can easily add a Bool flag like stepperHidden which controls whether the stepper is visible in your configureCell method. If you want all steppers to be hidden, set all flags to true and call tableView.reloadData()
Your tableView method would look like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "medicalTableViewCell") as! medicalTableViewCell
let medicine = medicines[indexPath.row]
cell?.configureCell(with: medicine)
return cell
}
and correspondingly,
public func configureCell(_ medicine: Medicine){
medicalName.text = medicine.name
medicalCount.text = "\(medicine.count)"
// stepper.isHidden = medicine.stepperHidden
}
First: How would I be able to pass data from the ItemVC Cell to the CartVC on button Clicked (Add To Cart Button(ATC)) in the selected cell, since I am no trying to use didSelectRowAt to pass the data to the CartVC. but the ATC btn to pass the cells data to the CartVC
my Segue from the ItemVC to the CartVC is in the BarButtonItem(cartBtn) so I dont want to jump to the CartVc when pressing the ATC button but only pass selected items data to CartVC when the ATC is pressed
Second how would I be able to pass the increment/decrement value in lblQty to to the CartVC when the ATC is pressed as well to be able to present a more accurate Subtotal
import UIKit
import SDWebImage
import Firebase
class ItemCell: UITableViewCell {
weak var items: Items!
#IBOutlet weak var name: UILabel!
#IBOutlet weak var category: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var weight: UILabel!
#IBOutlet weak var price: UILabel!
#IBOutlet weak var lblQty: UILabel!
#IBOutlet weak var addToCart: RoundButton!
#IBOutlet weak var plusBtn: RoundButton!
#IBOutlet weak var minusBtn: RoundButton!
func configure(withItems : Items) {
name.text = product.name
category.text = items.category
image.sd_setImage(with: URL(string: items.image))
price.text = items.price
weight.text = items.weight
}
}
import UIKit
import Firebase
import FirebaseFirestore
class ItemViewController: UITableViewController {
#IBOutlet weak var cartBtn: BarButtonItem!!
#IBOutlet weak var tableView: UITableView!
var itemSetup: [Items] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
fetchItems { (items) in
self.itemSetup = items.sorted
self.tableView.reloadData()
}
}
func fetchItems(_ completion: #escaping ([Items]) -> Void) {
// -** FireStore Code **-
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? CartViewController {
vc.items = self.itemSetup
}
}
#objc func plusItem(_ sender: UIButton) {
// -** increase Qty Code **-
}
//Function to decrement item count
#objc func minusItem(_ sender: UIButton) {
// -** decrease Qty Code **-
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as? ItemCell else { return UITableViewCell() }
cell.configure(withItem: itemSetup[indexPath.row])
cell.lblQty.text = "\(self.imageSetup[indexPath.row].count)"
cell.plusBtn.tag = indexPath.row
cell.plusBtn.addTarget(self, action: #selector(self.plusItem(_:)), for: .touchUpInside)
cell.minusBtn.tag = indexPath.row
cell.minusBtn.addTarget(self, action: #selector(self.minusItem(_:)), for: .touchUpInside)
return cell
}
}
class CartViewController: UIViewController {
var items: Items!
#IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cartTableView.dataSource = self
cartTableView.delegate = self
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Cart.currentCart.cartItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.qty.text = "\(cart.qty)"
cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"
cell.imageUrl // can't figure out how to pass image
return cell
}
}
import Foundation
class CartItem {
var items: Items
var qty: Int
init(items: Items, qty: Int) {
self.items = items
self.qty = qty
}
}
class Cart {
static let currentCart = Cart()
var cartItems = [CartItem]()
}
Just create a protocol to create a delegate and assign it to your cart class when the cell is initialized
protocol ItemCellDelegate {
func itemCell(didTapButton button: UIButton)
}
Then have a delegate property in the ItemCell
class ItemCell {
weak var delegate: ItemCellDelegate?
...
// Then call the delegate method when the buttons is tapped.
func buttonTapped() {
delegate?.itemCell(didTapButton: theCellsButton)
}
}
Then make your Cart conform to the delegate
extension Cart: ItemCellDelegate {
func itemCell(didTapButton button: UIButton) {
// Do you stuff with button, or any other data you want to pass in
}
}
Then set the delegate before the cell is returned.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.CartItems[indexPath.row]
cell.qty.text = "\(cart.qty)"
cell.lblMealName.text = "\(cart.items.category): \(cart.items.name)"
cell.lblSubTotal.text = "$\(cart.items.price1 * Float(cart.qty))"
cell.delegate = Cart.currentCart //You should rename this static var to just 'current'
return cell
}
I have to do this implementation, I need a list of cells representing month periods, where each one is collapsed, and when clicked it shows its content, I used two cells prototypes based on some tutorials I found but I'm really new into swift programming, I can't get the expected result, I share some screens and actual code. Hope someone could help me.
class BillingListCell: UITableViewCell{
#IBOutlet weak var billWrapper: UIView!
#IBOutlet weak var billTotal: 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 BillingListHeaderCell: UITableViewCell{
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var numberLabel: UILabel!
#IBOutlet weak var statusButton: UIButton!
func setExpanded() {
statusButton.setImage(UIImage(systemName: "chevron.up"), for: .normal)
}
func setCollapsed() {
statusButton.setImage(UIImage(systemName: "chevron.down"), for: .normal)
}
}
class BillingListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var billingListTableView: UITableView!
var paymentArray: [String] = ["data","data2", "data3"]
private let numberOfActualRowsForSection = 1
func numberOfSections(in tableView: UITableView) -> Int {
return paymentArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// First will always be header
return false ? (1+numberOfActualRowsForSection) : 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row == 0){
let cell = tableView.dequeueReusableCell(withIdentifier: "BillingListHeaderCell", for: indexPath) as! BillingListHeaderCell
cell.setCollapsed()
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: "BillingListCell", for: indexPath) as! BillingListCell
cell.billWrapper.layer.cornerRadius = 15
cell.billWrapper.layer.borderWidth = 1
cell.billWrapper.layer.borderColor = UIColor.blue.cgColor
cell.billTotal.text = "1234"
return cell
}
}
There is a task. Each cell contains a button by clicking which you want to delete this cell. The problem is that sections are used to delineate the entire list by category. The data I take from Realm DB. removal must occur under two conditions because the name is repeated, so you need to consider the name from the label and the name of the section. I will be very grateful for the sample code with comments.
import UIKit
import RealmSwift
class PurchesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var purchesTableView: UITableView!
let manage = ManagerData()
override func viewDidLoad() {
super.viewDidLoad()
purchesTableView.delegate = self
purchesTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
purchesTableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return manage.loadPurchases().0.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return manage.loadPurchases().0[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return manage.loadPurchases().1[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "purchesCell", for: indexPath) as! CustomPurchesTableViewCell
cell.productLabel.text = manage.loadPurchases().1[indexPath.section][indexPath.row]
cell.weightProductLabel.text = manage.loadPurchases().2[indexPath.section][indexPath.row]
cell.weightNameLabel.text = manage.loadPurchases().3[indexPath.section][indexPath.row]
// cell.boughtButton.addTarget(self, action: #selector(removeProduct), for: .touchUpInside)
return cell
}
}
class CustomPurchesTableViewCell: UITableViewCell {
#IBOutlet weak var boughtButton: UIButton!
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var weightProductLabel: UILabel!
#IBOutlet weak var weightNameLabel: UILabel!
#IBAction func removePurches(_ sender: Any) {
print("remove")
}
}
method for get data
func loadPurchases() -> ([String], Array<Array<String>>, Array<Array<String>>, Array<Array<String>>) {
var sections: [String] = []
var product = Array<Array<String>>()
var weight = Array<Array<String>>()
var nameWeight = Array<Array<String>>()
let realm = try! Realm()
let data = realm.objects(Purches.self)
for item in data {
if sections.contains(item.nameDish) == false {
sections.append(item.nameDish)
}
}
for a in sections {
var productArr = Array<String>()
var weightArr = Array<String>()
var nameWeightArr = Array<String>()
for prod in data {
if a == prod.nameDish {
productArr.append(prod.product)
weightArr.append(prod.weight)
nameWeightArr.append(prod.nameWeigh)
}
}
product.append(productArr)
weight.append(weightArr)
nameWeight.append(nameWeightArr)
}
return (sections, product, weight, nameWeight)
}
Index path you will get in cell class
Index path have two property section and row for table view
Now you can create on more method in Controller class and assign to a variable to every cell or you can use editAction provided by table view for delete
in order to get number section and row you need create IBOutlet in custom cell and on ViewController class is created addTarget for your button.
Example code at the bottom.
import UIKit
import RealmSwift
class PurchesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var purchesTableView: UITableView!
let manage = ManagerData()
//... more code ...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "purchesCell", for: indexPath) as! CustomPurchesTableViewCell
cell.productLabel.text = manage.loadPurchases().1[indexPath.section][indexPath.row]
cell.weightProductLabel.text = manage.loadPurchases().2[indexPath.section][indexPath.row]
cell.weightNameLabel.text = manage.loadPurchases().3[indexPath.section][indexPath.row]
cell.boughtButton.addTarget(self, action: #selector(removePurches(_:)), for: .touchUpInside)
return cell
}
#objc func removePurches(_ sender: UIButton) {
let position: CGPoint = sender.convert(CGPoint.zero, to: purchesTableView)
let indexPath: IndexPath! = self.purchesTableView.indexPathForRow(at: position)
print("indexPath.row is = \(indexPath.row) && indexPath.section is = \(indexPath.section)")
purchesTableView.deleteRows(at: [indexPath], with: .fade)
}
}
and custom class CustomPurchesTableViewCell for cell
class CustomPurchesTableViewCell: UITableViewCell {
#IBOutlet weak var boughtButton: UIButton! // you button for press
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var weightProductLabel: UILabel!
#IBOutlet weak var weightNameLabel: UILabel!
}