the table view cells not release from memory - swift3

i hope all is well
i have an issue with cell in table view it's not releasing when i scrolling in table view the following is my code
class MovieDownloadedTableViewCell: UITableViewCell {
#IBOutlet weak var movieImageView: UIImageView!
#IBOutlet weak var movieNameLabel: UILabel!
#IBOutlet weak var movieEmptyCircleImageView: UIImageView!
#IBOutlet weak var movieCheckMarkImageView: UIImageView!
var fetchURL:URL? {
didSet {
updateUI()
}
}
func updateUI() {
movieImageView.image = nil
movieNameLabel.text = nil
movieEmptyCircleImageView.isHidden = true
movieCheckMarkImageView.isHidden = true
if let fetchURL = fetchURL {
if fetchURL.pathExtension == "" {
movieImageView.image = UIImage(named: "folder")
}else{
movieImageView.image = UIImage(named: "movie")
}
movieNameLabel.text = fetchURL.lastPathComponent
}// end the if let
}// end the func updateUI
}// end the class
the above my custom table view cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MovieDownloadedTableViewCell
// defining the cell
if let cell = cell {
cell.tintColor = UIColor.white
cell.fetchURL = operationDocumentDirectoryObject.arrayOfMovieURL?[indexPath.row]
if isShowToolBar {
if operationDocumentDirectoryObject?.arrayOfShowAllEmptyCircle?[indexPath.row] == indexPath.row {
cell.movieEmptyCircleImageView.isHidden = false
}// end the if
if operationDocumentDirectoryObject.dictionaryHoldIndexCellForDisplayWhichCellSelected.count > 0 {
if operationDocumentDirectoryObject.dictionaryHoldIndexCellForDisplayWhichCellSelected[indexPath.row] == indexPath.row {
cell.movieEmptyCircleImageView.isHidden = true
cell.movieCheckMarkImageView.isHidden = false
}
}
}// end if for the isShowVar
}// end the creating cell
return cell!
}
please where my wrong code how can i make my table view cell when i scrolling is releasing from memory every time
thank you very much

Related

Custom delegate is always nil

I have a problem with my delegate use in a protocol, many person face the same problem but no answer works for me.
My first class is FavorisHeaderTableView
import UIKit
protocol FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell)
}
class FavorisHeaderTableViewCell: UITableViewCell {
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var txtFavoriteNameInput: UITextField!
#IBOutlet weak var lblIcon: UILabel!
#IBOutlet weak var lblTime: UILabel!
#IBOutlet weak var lblDescription: UILabel!
#IBOutlet weak var btnFavHeart: UIButton!
#IBOutlet weak var btnFavHome: UIButton!
#IBOutlet weak var btnFavShop: UIButton!
#IBOutlet weak var btnFavWork: UIButton!
#IBOutlet weak var btnFavGolf: UIButton!
var myDelegate: FavorisHeaderDelegate? = nil
var defaultIcon:FavIconType = .heart
var selectedIcon:UIButton? = nil {
didSet {
selectedIcon!.backgroundColor = Design.Palette.red
selectedIcon?.layer.cornerRadius = 3
selectedIcon?.tintColor = Design.Palette.white
}
willSet {
if selectedIcon != nil {
selectedIcon!.backgroundColor = UIColor.clear
selectedIcon?.tintColor = UIColor(red:0.671, green:0.651, blue:0.635, alpha:1)
}
}
}
#IBAction func didSelectIcon(_ sender: UIButton) {
selectedIcon = sender
self.myDelegate?.changeFavoris(sender: self)
}
#IBAction func changeTitle(_ sender: Any) {
txtFavoriteNameInput.text = "gare centro"
print("delegate: ",myDelegate)
if myDelegate != nil {
myDelegate?.changeFavoris(sender: self)
}
}
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
}
}
The second class who use the protocol is
addFavoriteViewController: UIViewController {
// MARK properties
let defaultLocalizer = AMPLocalizeUtils.defaultLocalizer
var favorisName:String? = nil
var defaultIcon:FavIconType = .heart
var delegate:handleFavorite? = nil
#IBOutlet weak var favTableView: UITableView!
var headerCell:FavorisHeaderTableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
// Localization of labels
//lblAddToFavorite.text = defaultLocalizer.stringForKey(key: "str_favorites_addTitle")
//lblFavoriteName.text = defaultLocalizer.stringForKey(key: "str_favorites_nameInput")
favTableView.delegate = self
favTableView.dataSource = self
self.headerCell?.myDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
// Text Field
//favorisName.clearButtonMode = .whileEditing
}
var place:PlaceModel? = nil
var itinerary:(source:PlaceModel, destination:PlaceModel)? = nil
let db = DataController.shared
var favorite:FavoritesMO? = nil
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UGOaddFavoriteViewController: FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell) {
defaultIcon = sender.defaultIcon
favorisName = sender.txtFavoriteNameInput.text
}
}
When I try this code "myDelegate" is always nil and I don't understand what's wrong despite of all topic read about this problem.
You are setting self as the delegate of the wrong cell!
Here:
self.headerCell?.myDelegate = self
you set the headerCell's delegate to self, but headerCell is never actually displayed on the screen!
You need to actually set the delegates of the cells on the screen, not the delegate of a random cell that you created.
The best place to do this is cellForRowAtIndexPath:
let cell = tableView.dequeueResusableCell(withIdentifier:...)!
// configure your cell
cell.delegate = self // set the delegate here!

fetch name from collection view cell while clicking on checkbox

I have name and image in collection view cell. I want to fetch names which I've selected on clicking checkbox in that particular cell. How do I do this??
Below is my code in collection view
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MyCollectionViewCell
cell.imgView.sd_setImage(with: URL(string: str1+self.nameArr [indexPath.row]), placeholderImage: UIImage(named: ""))
cell.lblName.text = self.nameArr [indexPath.row]
cell.lblTime.text = self.timeArr [indexPath.row]
return cell
}
Here's my cell file:
class MyCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var checkButton: UIButton!
#IBOutlet var imgView: UIImageView!
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var lblTime: UILabel!
var tickCheck:Bool = false
#IBAction func btnCheck(_ sender: Any)
{
if tickCheck == false
{
checkButton.setBackgroundImage(UIImage(named: "check"), for: .normal)
tickCheck = true
}
else
{
checkButton.setBackgroundImage(UIImage(named: "uncheck"), for: .normal)
tickCheck = false
}
}
}
Your CollectionView
class collectionVC: UIViewController,CellDelegate {
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MyCollectionViewCell
cell.imgView.sd_setImage(with: URL(string: str1+self.nameArr [indexPath.row]), placeholderImage: UIImage(named: ""))
cell.lblName.text = self.nameArr [indexPath.row]
cell.lblTime.text = self.timeArr [indexPath.row]
cell.checkButton.tag = indexPath.item
cell.delegateCell = self
cell.indexPath = indexPath
return cell
}
//Mark:- Did tap cell
func didTapCell(index: IndexPath){
let name = self.nameArr[index.item]
print("Your name >> \(name)")
}
}
Collection Cell
protocol CellDelegate: class {
func didTapCell(index: IndexPath)
}
class MyCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var checkButton: UIButton!
#IBOutlet var imgView: UIImageView!
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var lblTime: UILabel!
var delegateCell:CellDelegate?
var indexPath:IndexPath?
var tickCheck:Bool = false
#IBAction func btnCheck(_ sender: Any)
{
delegateCell?.didTapCell(index: indexPath!)
if tickCheck == false
{
checkButton.setBackgroundImage(UIImage(named: "check"), for: .normal)
tickCheck = true
}
else
{
checkButton.setBackgroundImage(UIImage(named: "uncheck"), for: .normal)
tickCheck = false
}
}
}

Swift 3.1 Label in TableViewCell - unexpectedly found nil

I'm trying to create two tableViews in one UIViewController. But when I'm trying to assign value to UILabel, getting an error: fatal error: unexpectedly found nil while unwrapping an Optional value
I wonder why, I have almost the same code for TableViewController with one tableView and it works with no issues. It looks like these UI Labels are not initialized when trying to assign value to it. But don't understand how to fix it.
It fails here:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
if tableView == self.guestsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestAtTableTableViewCell
if let guestsTable = guestsTableFetchedResultsController?.object(at: indexPath) {
print(guestsTable.guestName) // works fine, prints the value
print(cell.guestNameLabel.text) //fails here with error fatal error: unexpectedly found nil while unwrapping an Optional value
cell.guestNameLabel.text = guestsTable.guestName
cell.openTimeLabel.text = String(describing: guestsTable.openTime)
cell.cellDelegate = self
}
}
else if tableView == self.ordersTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath)
//to be done
}
// Configure the cell...
return cell!
}
Full code of this class:
import UIKit
import CoreData
class TableUIViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CellWithButtonDelegate {
//The following two variables will not be nil because prepare for segue will set them
var tableName: String?
var table: TablesTable? = nil
fileprivate var currentTableSession: TableSessionTable? {
get {
let tableSessionTable = TableSessionTable()
return tableSessionTable.getCurrentTableSession(table: table!)
}
}
fileprivate var guestsTableFetchedResultsController: NSFetchedResultsController<GuestsTable>?
fileprivate var ordersTableFetchedResultsController: NSFetchedResultsController<OrdersTable>?
#IBOutlet weak var tableNameLabel: UILabel!
#IBOutlet weak var tableCapacityLabel: UILabel!
#IBOutlet weak var tableCountOfGuestsLabel: UILabel!
#IBOutlet weak var tableDescriptionTextView: UITextView!
#IBAction func closeTableButtonPressed(_ sender: UIButton) {
}
#IBOutlet weak var guestsTableView: UITableView!
#IBOutlet weak var ordersTableView: UITableView!
#IBAction func addGuestButtonPressed(_ sender: UIButton) {
let guestsTable = GuestsTable()
let tablesTable = TablesTable()
let table = Table(tableName: tableName!, tableCapacity: 0, locationX: nil, locationY: nil, tableImage: nil)
try? guestsTable.addNewGuest(table: tablesTable.getOrCreateTable(table: table))
updateUI()
}
#IBAction func addOrderButtonPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
guestsTableView.dataSource = self
guestsTableView.delegate = self
guestsTableView.register(GuestAtTableTableViewCell.self, forCellReuseIdentifier: "guestCell")
ordersTableView.dataSource = self
ordersTableView.delegate = self
ordersTableView.register(UITableViewCell.self, forCellReuseIdentifier: "orderCell")
updateUI()
}
func didPressButton(table: TablesTable) {
}
private func updateUI () {
let tableView = guestsTableView
let context = AppDelegate.viewContext
let request : NSFetchRequest<GuestsTable> = GuestsTable.fetchRequest()
request.predicate = NSPredicate(format: "table= %#", currentTableSession!)
request.sortDescriptors = [NSSortDescriptor(key: "guestName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
guestsTableFetchedResultsController = NSFetchedResultsController<GuestsTable>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
try? guestsTableFetchedResultsController?.performFetch()
tableView?.reloadData()
}
private func updateUI1 () {
let tableView = ordersTableView
let context = AppDelegate.viewContext
let request : NSFetchRequest<OrdersTable> = OrdersTable.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "menuItem", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
ordersTableFetchedResultsController = NSFetchedResultsController<OrdersTable>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
try? ordersTableFetchedResultsController?.performFetch()
tableView?.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
if tableView == self.guestsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestAtTableTableViewCell
if let guestsTable = guestsTableFetchedResultsController?.object(at: indexPath) {
print(guestsTable.guestName) // works fine, prints the value
print(cell.guestNameLabel.text) //fails here with error fatal error: unexpectedly found nil while unwrapping an Optional value
cell.guestNameLabel.text = guestsTable.guestName
cell.openTimeLabel.text = String(describing: guestsTable.openTime)
cell.cellDelegate = self
}
}
else if tableView == self.ordersTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath)
//to be done
}
// Configure the cell...
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == self.guestsTableView {
return guestsTableFetchedResultsController?.sections?.count ?? 1
}
else if tableView == self.ordersTableView {
return ordersTableFetchedResultsController?.sections?.count ?? 1
}
else {return 1}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.guestsTableView {
if let sections = guestsTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
}
else {
return 0
}
}
else if tableView == self.ordersTableView {
if let sections = ordersTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
}
else {
return 0
}
}
else {return 0}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == self.guestsTableView {
if let sections = guestsTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
}
else {
return nil
}
}
else if tableView == self.ordersTableView {
if let sections = ordersTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
}
else {
return nil
}
}
else {return nil}
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if tableView == guestsTableView {
return guestsTableFetchedResultsController?.sectionIndexTitles
}
else {
return ordersTableFetchedResultsController?.sectionIndexTitles
}
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if tableView == guestsTableView {
return guestsTableFetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
else if tableView == ordersTableView {
return ordersTableFetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
else {return 0}
}
}
And full code of UITableViewCell class:
import UIKit
class GuestAtTableTableViewCell: UITableViewCell {
weak var cellDelegate: CellWithButtonDelegate?
#IBOutlet weak var guestNameLabel: UILabel!
#IBOutlet weak var openTimeLabel: UILabel!
#IBAction func didPressButton(_ sender: UIButton) {
}
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 guess you have a xib for your UITableViewCell register the xib instead of the class.
Use the following:
guestsTableView.register(UINib.init(nibName: "GuestAtTableTableViewCell", bundle: nil), forCellReuseIdentifier: "guestCell")
As you have created a prototype cell in the storyboard itself you should select the cell in the storyboard and set its identifier there. Next remove the register line from your code for guestCell. It should work

How to save the google Placepicker locations to tableviewcell?

I have written this code, i want the picker location to be saved to tableview cells every time i pick the place from place picker.
As of now only one place, i am able to save. I have tried searching in google and other things didn't get correct one. Can anyone help me with this.
class SetLocationLocationsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var setLocationImagePin: UIImageView!
#IBOutlet weak var ClearLabel: UILabel!
#IBOutlet weak var DeleteButton: UIButton!
#IBOutlet weak var SetLocationView: UIView!
#IBOutlet weak var PickUpLocationButton: UIButton!
#IBOutlet weak var AddressTextField: UITextField!
#IBOutlet weak var LocationButton: UIButton!
#IBOutlet weak var NameLabel: UILabel!
#IBOutlet weak var tableViewForLocations: UITableView!
var placesClient: GMSPlacesClient!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
AddressTextField.isHidden = true
tableViewForLocations.delegate = self
tableViewForLocations.dataSource = self
AddressTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
#IBAction func PickPlace(_ sender: Any) {
let center = CLLocationCoordinate2D(latitude: 37.788204, longitude: -122.411937)
let northEast = CLLocationCoordinate2D(latitude: center.latitude + 0.001, longitude: center.longitude + 0.001)
let southWest = CLLocationCoordinate2D(latitude: center.latitude - 0.001, longitude: center.longitude - 0.001)
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePicker(config: config)
AddressTextField.isHidden = false
placePicker.pickPlace(callback: {(place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let place = place {
self.NameLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
} else {
self.NameLabel.text = ""
}
})
}
#IBAction func SetLocationClicked(_ sender: Any) {
tableViewForLocations.reloadData()
AddressTextField.isHidden = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewForLocations.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! LocationCell
cell.Label1.text = AddressTextField.text
cell.Label2.text = NameLabel.text
tableViewForLocations.register(UITableViewCell.self, forCellReuseIdentifier: "mycell")
return cell
}
#IBAction func DeleteClicked(_ sender: Any) {
}
}

Getting Values from UISliders alongside UserID (linking User to section number?)

I'm working on creating a 'Rate' feature in my app where it pulls the users to rate from an external API. I then create a TableView which adds cells that contain a section name (the name of the User) and a UISlider.
What I'm trying to do is gather the data from the UISliders along with the User ID associated with the User who's section it is so that I can call a POST action to the API to send the rating data too.
Here's the code I have: (For the record, first time with Swift, the comments are me trying to figure out how to do this). Any ideas?
import UIKit
import Alamofire
class RateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var submitButton: UIButton!
#IBOutlet weak var activeSurveyLabel: UILabel!
private var myTableView: UITableView!
var usersToRate = [User]()
var activeSurveyId: String?
var rateData = [String: Int]()
var sectionIdToUserId = [Int: String]()
var userIdSection = [Int: String]()
override func viewDidLoad() {
super.viewDidLoad()
submitButton.isHidden = true
submitButton.addTarget(self, action: #selector(pressSubmitButton(button:)), for: UIControlEvents.touchUpInside)
activeSurveyLabel.isHidden = false
self.loadUsersToRate()
Alamofire.request(RateRouter.getSurvey()).responseJSON { response in
debugPrint(response)
if let string = response.result.value as? [[String: Any]]{
if string.count == 0 {
return
}
self.submitButton.isHidden = false
self.activeSurveyLabel.isHidden = true
for survey in string {
if let survey = Survey(json: survey) {
self.activeSurveyId = survey._id!
print(survey._id!)
}
}
//if there's a result, show slider bars for each person on the team with rating scales (except for the person logged in)
//have a submit button with a post request for the votes
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = barHeight * CGFloat(self.usersToRate.count * 5)
self.myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
self.myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
self.myTableView.dataSource = self
self.myTableView.delegate = self
self.view.addSubview(self.myTableView)
} else {
print(response.result.error!)
let label = UILabel()
label.center = self.view.center
label.text = "No Active Surveys"
self.view.addSubview(label)
}
}
// Do any additional setup after loading the view.
}
func loadUsersToRate() {
Alamofire.request(RateRouter.getUsers()).responseJSON { response in
guard let jsonArray = response.result.value as? [[String: Any]] else {
print("didn't get array, yo")
return
}
for item in jsonArray {
if let user = User(json: item) {
self.usersToRate.append(user)
self.rateData.updateValue(5, forKey: user.userId!) //initialize user average data at 5 in case they don't change it
print (self.rateData)
}
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(usersToRate[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
self.sectionIdToUserId.updateValue(usersToRate[section].userId!, forKey: section)
print(self.sectionIdToUserId)
return "\(usersToRate[section].name!)"
}
func numberOfSections(in tableView: UITableView) -> Int {
return usersToRate.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
let slider = UISlider(frame: CGRect(x: 0, y:0, width: 400, height: 44))
slider.isUserInteractionEnabled = true
slider.minimumValue = 1
slider.maximumValue = 10
slider.value = 5
slider.tag = indexPath.section
slider.addTarget(self, action: #selector(sliderValueChange(sender:)), for: UIControlEvents.valueChanged)
cell.addSubview(slider)
return cell
}
func sliderValueChange(sender: UISlider) {
//get slider value
var currentValue = Int(sender.value)
print(currentValue)
//self.rateData.updateValue(currentValue, forKey: self.sectionIdToUserId.values[sender.])
//get user id for that value
//self.rateData.updateValue(currentValue, rateData[section])
// self.rateData.updateValue(currentValue, forKey: 0)
}
func pressSubmitButton(button: UIButton) {
for user in usersToRate {
// Alamofire.request(RateRouter.vote(voteFor: user.userId!, survey: activeSurveyId, rating:))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
To answer my own question, what I did was create a different model called 'Votes' that stored the information for each vote.
Then to fill that array I created a tag for the slider in the tableView based on the section ID and used that to update the current value.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
let slider = UISlider(frame: CGRect(x: 0, y:0, width: cell.frame.width , height: 44))
slider.tag = indexPath.section
slider.addTarget(self, action: #selector(sliderValueChange(sender:)), for: UIControlEvents.valueChanged)
cell.addSubview(slider)
return cell
}
func sliderValueChange(sender: UISlider) {
//get slider value
var currentValue = Int(sender.value)
print(currentValue)
voteData[sender.tag].rating = currentValue
}