Can't Click on button in tableView cell after reloadData - ios

I have in cell implement 3 buttons and button action. After call tableView.reloadData() can't click to any button in cell.
In controller in func cellForRow call cell?.onbuttonTappedAdd and other. Afer add element I call tabelViewReloadData.
//TableViewCell
var onButtonTappedAdd : (() -> Void)? = nil
var onButtonTappedRemove : (() -> Void)? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(orderitem: OrderItem){
self.orderItem = orderitem!
}
func setButtonGradient(){
}
#IBAction func changeValue(_ sender: Any) {
}
#IBAction func btnAddValue(_ sender: Any) {
if let onButtonTappedAdd = self.onButtonTappedAdd
{
onButtonTappedAdd()
}
}
#IBAction func btnRemoveValue(_ sender: Any) {
if let onButtonTappedRemove = self.onButtonTappedRemove {
onButtonTappedRemove()
}
}
//ViewControll cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableViewOrderItem.dequeueReusableCell(withIdentifier: "OrderItemCheckoutCell", for: indexPath)
as? OrderItemCheckoutCell
var orderItem = GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row]
cell?.configureCell(orderitem: orderItem)
cell?.onButtonTappedAdd = {
GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].quantity = GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].quantity! + (GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].Product?.bigValue)!
self.tableViewOrderItem.reloadData()
self.setTotalInfo()
}
cell?.onButtonTappedRemove = {
GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].quantity = GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].quantity! - (GlobalArray.orderArrayList[indexPath.section].ListOrderItem[indexPath.row].Product?.bigValue)!
self.tableViewOrderItem.reloadData()
}
return cell!
}

Reload TableView Outside of the "cellforRow" method

Related

Protocol Delegate Does not Trigger Swift

I want to trigger MultipleAnswerTableViewCell's mainSaveTapped func when the IBAction saveButton tapped.
Here is my class with the protocol
protocol AddQuestionViewControllerDelegate: AnyObject {
func mainSaveTapped()
}
class AddQuestionViewController: BaseViewController, MultipleAnswerTableViewCellDelegate, UITextFieldDelegate {
weak var delegate: AddQuestionViewControllerDelegate?
#IBAction func saveTapped(_ sender: UIButton) {
delegate?.mainSaveTapped()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch cellTypes[indexPath.row] {
case .fixedTop: return configureFixedTop(indexPath: indexPath)
case .multiAnswer: return configureMultiAnswerCell(indexPath: indexPath)
case .singleAnswer: return configureSingleAnswerCell(indexPath: indexPath)
case .textAnswer: return configureTextAnswerCell(indexPath: indexPath)
}
}
func configureMultiAnswerCell(indexPath: IndexPath) -> MultipleAnswerTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
cell.parentVC = self
cell.answerDelegate = self
cell.setupMultipleAnswerView()
return cell
}
And this is my MultipleAnswerTableViewCell
protocol MultipleAnswerTableViewCellDelegate: AnyObject {
func sendAnswers(surveyAnswers: [SurveyAnswer])
}
class MultipleAnswerTableViewCell: UITableViewCell, AddQuestionViewControllerDelegate, UITextFieldDelegate {
weak var answerDelegate: MultipleAnswerTableViewCellDelegate?
func mainSaveTapped() {
checkPostShare()
}
My func mainSaveTapped never triggered hence checkPostShare never called. What should I do to trigger mainSaveTapped func inside the MultipleAnswerTableViewCell
You don't assign a value to the delegate property inside the vc
weak var delegate: AddQuestionViewControllerDelegate?
So here delegate? is nil
#IBAction func saveTapped(_ sender: UIButton) {
delegate?.mainSaveTapped() // delegate? is nil
}
You need to send a message from the vc to the cell , here you don't need a delegate ,instead
#IBAction func saveTapped(_ sender: UIButton) {
(tableView.visibleCells as? [MultipleAnswerTableViewCell])?.forEach { cell in
cell.mainSaveTapped()
}
}

Expandable drop down with Multi select checkbox in Swift

check / uncheck the check box by tapping the cell in table view and how to know which cell has checked or unchecked inside Expandable drop down in Swift.
VBExpandVC
class VBExpandVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var myTableView: UITableView!
struct Notification:Codable {
let notification:[Headings]
}
struct Headings:Codable {
var name:String
var status:Int
}
var names = [Headings]()
var expandTableview:VBHeader = VBHeader()
var cell : VCExpandCell!
override func viewDidLoad() {
super.viewDidLoad()
getNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
expandTableview = Bundle.main.loadNibNamed("VBHeader", owner: self, options: nil)?[0] as! VBHeader
let layer = expandTableview.viewHeader.layer
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 0.4
expandTableview.lblDate.text = self.names[section].name
expandTableview.btnExpand.tag = section
expandTableview.btnExpand.addTarget(self, action: #selector(VBExpandVC.headerCellButtonTapped(_sender:)), for: UIControl.Event.touchUpInside)
let str:String = "\(self.names[section].status)"//arrStatus[section] as! String
if str == "0"
{
UIView.animate(withDuration: 2) { () -> Void in
self.expandTableview.imgArrow.image = UIImage(named :"switch")
}
}
else
{
UIView.animate(withDuration: 2) { () -> Void in
self.expandTableview.imgArrow.image = UIImage(named :"switch2")
}
}
return expandTableview
}
#objc func headerCellButtonTapped(_sender: UIButton)
{
print("header tapped at:")
print(_sender.tag)
var str:String = "\(self.names[_sender.tag].status)"
if str == "0"
{
self.names[_sender.tag].status = 1
}
else
{
self.names[_sender.tag].status = 0
}
// myTableView.reloadData()
myTableView.reloadSections([_sender.tag], with: .none)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
//Return header height as per your header hieght of xib
return 40
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
let str:Int = (names[section].status)
if str == 0
{
return 0
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? VCExpandCell
return cell;
}
func numberOfSections(in tableView: UITableView) -> Int
{
return self.names.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
//Return row height as per your cell in tableview
return 111
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected:\(indexPath.section)")
}
// getNotifications
func getNotifications(){
guard let url = URL(string: "https://www.json-generator.com/api/json/get/cgAhRPmZgy?indent=2") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
guard let data = data, error == nil, response != nil else {
return
}
do {
let headings = try JSONDecoder().decode(Notification.self, from: data)
self.names = headings.notification
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch {
print(error)
}
}).resume()
}
// End
}
VCExpandCell
class VCExpandCell: UITableViewCell {
#IBOutlet weak var btnMobile: UIButton!
#IBOutlet weak var btnEmail: UIButton!
#IBOutlet weak var btnSms: 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
}
#IBAction func btnMobileApp(_ sender: UIButton) {
print("mobile app checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
#IBAction func btnSMS(_ sender: UIButton) {
print("sms checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
#IBAction func btnEmail(_ sender: UIButton) {
print("email checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
}
enter image description here
In the above code, I have two major problems.
selected check box positions are changing when expanded the section and expanded another section
Unable to find selected check boxes by tapping the cell in table view inside Expand drop down.
Have a look ont his given url:
https://github.com/AssistoLab/DropDown

Delegate between controllers doesn't work. Why?

I try to use delegate to send data from textField which is in the Detail2(ViewController) to array which is in the ViewController.
I used here print method and first print show that one element has been added to the array but the second print method which is below the ViewVillAppear() show that array is empty. How? I want to be able to to use delegate to add data to my table.
["sdsd"] First print from the console
[]Second print from the console
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var add: UIBarButtonItem!
#IBOutlet var tv: UITableView!
var array :[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let vc: Detail2 = segue.destination as! Detail2
vc.delegate = self
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
array.remove(at: indexPath.row )
tv.reloadData()
}
}
func alert () {
}
override func viewWillAppear(_ animated: Bool) {
tv.reloadData()
print(array)
}
}
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
}
}
and Detail2
protocol Data {
func tekst (data: String)
}
class Detail2: UIViewController {
var delegate: Data? = nil
#IBAction func btn(_ sender: Any) {
let sb = storyboard?.instantiateViewController(withIdentifier: "Main" ) as! ViewController
navigationController?.pushViewController(sb, animated: true)
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
}
#IBOutlet var btn: UIButton!
#IBOutlet var txtfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
btn.backgroundColor = UIColor.blue
btn.tintColor = UIColor.white
btn.layer.cornerRadius = 25
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Just update your function with:
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
navigationController?.popViewController(animated: true)
}
}
Update:
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
self.tv.reloadData()
}
}
You need to add this delegate?.tekst(data: napis!) inside completion handler, because you are using navigationController, there is no option for completion handler,So have to add UINavigationController extension like that:
extension UINavigationController {
public func pushViewController(viewController: UIViewController,
animated: Bool,
completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
pushViewController(viewController, animated: animated)
CATransaction.commit()
}
}
change this
navigationController?.pushViewController(sb, animated: true){
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
Update your code in Detail2 viewcontroller
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
navigationController?.popViewController(animated: true)
}
In the ViewController implement the delegate method
func tekst (data: String) {
array.append(data)
}
// in detail
#IBAction func btn(_ sender: Any) {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
/// dismiss detail here don't push main again
self.navigationController?.popViewController(animated: true)
}

Cell is not selectable embed UItableView inside main View?

I have UITableView embed inside a main UIView. My problem is when I click on a cell to select items, it is not responding to the selection or triggering the segue.
Note: In attributes inspecter
is selection supposed to be set to single selection?
Update Note: the prepareForSegue function is not triggering or print "test".
import UIKit
import SwiftValidator
import CoreData
class EditNpFormViewController: UIViewController,UITextFieldDelegate, UIViewControllerTransitioningDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(EditNpFormViewController.dismissKeybored)))
self.npVisitViewTable.dataSource = self
self.npVisitViewTable.delegate = self
loadValidaValidationSettings()
loadUIObjectsSetting()
populateUIobjects()
}
func loadValidaValidationSettings() {
validator.styleTransformers(success:{ (validationRule) -> Void in
// clear error label
validationRule.errorLabel?.hidden = true
validationRule.errorLabel?.text = ""
if let textField = validationRule.field as? UITextField {
textField.layer.borderColor = UIColor.greenColor().CGColor
textField.layer.borderWidth = 0.5
}
}, error:{ (validationError) -> Void in
print("error")
validationError.errorLabel?.hidden = false
validationError.errorLabel?.text = validationError.errorMessage
if let textField = validationError.field as? UITextField {
textField.layer.borderColor = UIColor.redColor().CGColor
textField.layer.borderWidth = 1.0
}
})
validator.registerField(firstNameTextField, errorLabel:firstNameErrorLabel , rules: [RequiredRule(), AlphaRule()])
validator.registerField(lastNameTextField, errorLabel:lastNameErrorLabel , rules: [RequiredRule(), AlphaRule()])
validator.registerField(brnTextFieled, errorLabel:brnErrorLabel, rules: [RequiredRule(), AlphaNumericRule()])
}
func loadUIObjectsSetting(){
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
self.brnTextFieled.delegate = self
self.pickerLhsc.dataSource = self
self.pickerLhsc.delegate = self
self.pickerLhsc.tag = 0
self.ltchTextFieled.inputView = pickerLhsc
self.ltchTextFieled.delegate = self
self.ltchTextFieled.hidden = true
}
func populateUIobjects(){
self.firstNameTextField.text = selectedNpForm!.patientFirstName
self.lastNameTextField.text = selectedNpForm!.patientLastName
self.brnTextFieled.text = selectedNpForm!.brnNumber
self.ltchTextFieled.text = pickerDataLtch.filter { $0.uniqId == selectedNpForm!.ltch }.first?.hospital ?? ""
self.isPatientLtchResidentSwitch.setOn((selectedNpForm!.isPatientLtchResident == 0 ?false : true), animated: true)
self.ltchTextFieled.hidden = !(isPatientLtchResidentSwitch.on ? true : false)
reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Methods
func dismissKeybored(){
firstNameTextField.resignFirstResponder()
lastNameTextField.resignFirstResponder()
brnTextFieled.resignFirstResponder()
ltchTextFieled.resignFirstResponder()
}
func textFieledShouldReturn(){
firstNameTextField.resignFirstResponder()
lastNameTextField.resignFirstResponder()
brnTextFieled.resignFirstResponder()
ltchTextFieled.resignFirstResponder()
}
func hideKeyboard(){
self.view.endEditing(true)
}
func validationSuccessful() {
print("Validation Success!")
}
func validationFailed(errors:[(Validatable, ValidationError)]) {
print("Validation FAILED!")
// turn the fields to red
for (field, error) in errors {
if let field = field as? UITextField {
field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0
}
error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.hidden = false
}
}
func reloadData(predicate: NSPredicate? = nil) {
if let selectedNpForm = selectedNpForm {
if let formVisits = selectedNpForm.visits?.allObjects {
npVisits = formVisits as! [NpVisit]
}
} else {
let fetchRequest = NSFetchRequest(entityName: "NpVisit")
fetchRequest.predicate = predicate
do {
if let results = try moc.executeFetchRequest(fetchRequest) as? [NpVisit] {
npVisits = results
}
} catch {
fatalError("There was an error fetching the list of devices!")
}
}
npVisitViewTable.reloadData()
}
//MARK: - #IBAction
#IBAction func EditBrn(sender: AnyObject) {
print("Validating...")
//validator.validate(self)
}
#IBAction func saveNpForm(sender: AnyObject) {
if let selectedNpFormId = moc.objectWithID(selectedNpForm!.objectID) as? NpForm{
selectedNpFormId.brnNumber = brnTextFieled.text
selectedNpFormId.patientFirstName = firstNameTextField.text
selectedNpFormId.patientLastName = lastNameTextField.text
selectedNpFormId.isPatientLtchResident = isPatientLtchResidentSwitch.on ? true : false
selectedNpFormId.ltch = hospitalUniqId
}
do {
try moc.save()
} catch let error as NSError {
print("Could not save \(error), \(error)")
}
}
#IBAction func dosePatientResideLtch(sender: AnyObject) {
self.ltchTextFieled.hidden = !(isPatientLtchResidentSwitch.on ? true : false)
}
// MARK: Validate single field
// Don't forget to use UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
validator.validateField(textField){ error in
if error == nil {
// Field validation was successful
} else {
// Validation error occurred
}
}
return true
}
//MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "addNewNoVisit"){
if let distination = segue.destinationViewController as? MapViewController{
distination.clientNpForm._patientFirstName = firstNameTextField.text!
distination.clientNpForm._patientLastName = lastNameTextField.text!
distination.clientNpForm._brnNumber = brnTextFieled.text!
distination.clientNpForm._isPatientLtchResident = isPatientLtchResidentSwitch.on ? true : false
distination.clientNpForm._ltch = hospitalUniqId
distination.editNpFormMode = editNpFormMode
distination.selectedNpForm = selectedNpForm
}
}
if (segue.identifier == "sendNpVisitToVisitDetailSegue"){
print("test segue fired ")
}
}
//MARK: - #IBOutlet
#IBOutlet weak var firstNameTextField: UITextField!
#IBOutlet weak var lastNameTextField: UITextField!
#IBOutlet weak var brnTextFieled: UITextField!
#IBOutlet weak var npVisitViewTable: UITableView!
#IBOutlet weak var firstNameErrorLabel: UILabel!
#IBOutlet weak var lastNameErrorLabel: UILabel!
#IBOutlet weak var brnErrorLabel: UILabel!
#IBOutlet weak var isPatientLtchResidentSwitch: UISwitch!
#IBOutlet weak var ltchTextFieled: UITextField!
#IBOutlet weak var saveNpForm: UIButton!
//MARK: -VARIABLES
let validator = Validator()
var pickerLhsc = UIPickerView()
var editNpFormMode = FormMode.Edit
var selectedNpForm = NpForm?()
var npVisits = [NpVisit]()
var moc = DataController().managedObjectContext
var hospitalUniqId:Int = 0
var pickerDataLtch:[(uniqId:Int,hospital:String)] = [(229,"hospital 1"),
(230,"hospital 2"),
(231,"hospital 3")]
}
extension EditNpFormViewController:UIPickerViewDataSource,UIPickerViewDelegate {
// MARK, - Picker View
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//return pickerDataLhsc.count
return pickerDataLtch.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
hospitalUniqId = pickerDataLtch[row].uniqId
ltchTextFieled.text = pickerDataLtch[row].hospital
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)-> String? {
return pickerDataLtch[row].hospital
}
}
extension EditNpFormViewController: UITableViewDelegate,UITableViewDataSource{
func tableView(npVisitViewTable: UITableView, numberOfRowsInSection section: Int) -> Int{
return npVisits.count
}
func tableView(npVisitViewTable: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell:UITableViewCell = npVisitViewTable.dequeueReusableCellWithIdentifier("visitCell")! as UITableViewCell
cell.textLabel?.text = "Visit #\(indexPath.row + 1)"
return cell
}
func tableView(npVisitViewTable: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(npVisitViewTable: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("selected row ")
}
}
In this answer I am making the assumption that didSelectRowAtIndexPath is firing.
In your didSelectRowAtIndexPath, you need to fire the segue that you created from the cell to the second view controller:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("selected row", indexPath)
performSegue(with: "segueIdentifier")
}
I'm not sure what version of Swift you are using, so you might need to make some slight changes.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//self.performSegue(withIdentifier: "sites", sender: self)
self.performSegue(withIdentifier: "CHANGE-TO-YOUT-SEGUE-ID", sender: self)
}
is the "hello" get printed? if so, call your segue from this point. Don't forget to connect your segue (from the top left square) in the story board as manual segue:
If func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) is not called at all, your problem is that the delegate of your UITableView is not set (or not correctly set). The delegate should be your EditNpFormViewController.
You can easily set the delegate of your UITableView instance by simply Control-dragging from the table to the controller that contains it (inside the Storyboard). The other simple way is by setting
tableView.delegate = self
You can just select the table inside the storyboard and drag the delegate from the right panel's circle to your controller:
If your delegate is set right, check the selection attribute of the cell itself:
If your table view is in editing mode, you need to set tableView.allowsSelectionDuringEditing = true

iOS unwind CollectionView at didSelectItemAtIndexPath

So i have created an app where users create custom workouts.
You enter the first view add a x number of rounds,than you click on a button in the tableview where you add rounds.That click opens another activity with a collectionview.
So the problem is here when i click on an element witch represents the exercise that needs to be in the round it sends me an empty result.By default if i add a value to that string it works.
I have noticed that the unwind happens before my didSelectItemAtIndexPath
import UIKit
class InsertWorkout: UIViewController{
#IBOutlet var InsertRoundTable: UITableView!
#IBOutlet weak var txtName: UITextField!
var RoundNumber : NSMutableArray = ["Round 1"]
var RoundLabel : NSMutableArray = [""]
var RoundExercise : NSMutableArray = ["add-1"]
var RoundExerciseImages : NSMutableArray = ["providno"]
var RoundNumber_Count=1
var RoundNumber_Add_Counter=1
var studentData : StudentInfo!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UIButton Action methods
#IBAction func btnBackClicked(sender: AnyObject)
{
self.navigationController?.popViewControllerAnimated(true)
}
#IBAction func btnSaveClicked(sender: AnyObject)
{
if(txtName.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter workout name.", delegate: nil)
}
else
{
let studentInfo: StudentInfo = StudentInfo()
studentInfo.workout_name = txtName.text!
studentInfo.workout_benefit_1=" CUSTOM "
studentInfo.workout_benefit_2=" WORKOUT "
studentInfo.workout_benefit_3=""
studentInfo.workout_requiremnets="arsutech.com"
studentInfo.workout_time="4min"
let isInserted = ModelManager.getInstance().addWorkoutData(studentInfo)
if isInserted {
Util.invokeAlertMethod("", strBody: "Workout added", delegate: nil)
} else {
Util.invokeAlertMethod("", strBody: "Error while adding workout.", delegate: nil)
}
self.navigationController?.popViewControllerAnimated(true)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
InsertRoundTable.endEditing(true)
}
//UITableView
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return RoundNumber.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : InsertRoundCell! = tableView.dequeueReusableCellWithIdentifier("InsertRoundCell") as! InsertRoundCell
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("InsertRoundCell", owner: self, options: nil)[0] as! InsertRoundCell;
}
let exerviseName = RoundNumber[indexPath.row]
let exerciseLabels = RoundLabel[indexPath.row]
let exerciseImage = RoundExercise[indexPath.row]
let exerciseImage_Holder = RoundExerciseImages[indexPath.row]
cell.insert_label_Round.text = exerviseName as? String
cell.addWorkout_Label.text = exerciseLabels as? String
cell.addExercise_Holder?.image = UIImage(named: exerciseImage_Holder as! String) as UIImage?
cell.addWorkoutBut.setBackgroundImage(UIImage(named: exerciseImage as! String) as UIImage?, forState: UIControlState.Normal)
cell.addWorkoutBut.tag = indexPath.row
cell.addWorkoutBut.addTarget(self, action: "logAction:", forControlEvents: .TouchUpInside)
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell as InsertRoundCell
}
#IBAction func logAction(sender: UIButton){
//self.RoundNumber.replaceObjectAtIndex(sender.tag, withObject: "Ezel")
//let titleString = self.RoundNumber[sender.tag] as? String
//Util.invokeAlertMethod("", strBody: titleString!, delegate: nil)
self.InsertRoundTable.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let destinationVC = segue.destinationViewController as! ChoseExercise
destinationVC.id=sender.tag
RoundNumber_Count=sender.tag
}
#IBAction func unwinndChoseExercise(segue:UIStoryboardSegue){
if let svc = segue.sourceViewController as? ChoseExercise{
self.RoundLabel.replaceObjectAtIndex(RoundNumber_Count, withObject: "\(svc.exercise_label)")
self.RoundExercise.replaceObjectAtIndex(RoundNumber_Count, withObject: "providno")
self.RoundExerciseImages.replaceObjectAtIndex(RoundNumber_Count, withObject: "\(svc.exercise_image)")
self.InsertRoundTable.reloadData()
}
}
//Add Round
#IBAction func addRound(sender: AnyObject) {
if(RoundNumber_Add_Counter<12){
RoundNumber_Add_Counter++
self.RoundNumber.addObject("Round \(RoundNumber_Add_Counter)")
self.RoundLabel.addObject("")
self.RoundExercise.addObject("add-1")
self.RoundExerciseImages.addObject("providno")
self.InsertRoundTable.reloadData()
}else{
Util.invokeAlertMethod("", strBody: "This is the maximum number of rounds", delegate: nil)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.exercisesNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellexercises_insert", forIndexPath: indexPath) as! Insert_ExerciseCollectionViewCell
cell.insert_exerciseImage?.image = self.exercisesImages[indexPath.row]
cell.insert_exerciseLabel?.text = self.exercisesNames[indexPath.row]
cell.insert_exercisesHardnessImg?.image = self.exercisesHardnessImg[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
exercise_label="\(exercisesNames[indexPath.row])"
exercise_image="\(exercises_Exervise_Row_Names[indexPath.row])"
dismissViewControllerAnimated(true, completion: nil)
}
Here is how unwinding works:
First, put your IBAction unwind(segue:UIStoryboardSegue) in the vc where you intend to go back (presenter vc, InsertWorkout in this case).
Second, go to storyboard and choose the vc where you'll unwind from (collection view in this case) and ctrl-drag from the button/cell that causes the unwind (collection view cell in your case) to the exit button on top of that same vc and you should see a pop-up with your IBAction unwind method name under 'Selection Segue'.
Third, implement prepareforsegue in the current vc (collection vc in this case) to pass your data back.
class InsertWorkout
{
IBAction func unwind(segue:UIStoryboardSegue) {
//use the data passed from prepare to update your ui or you can also communicate to the sender using segue.sourceVC
}
}
class CollectionVC
{
override func prepareForSegue(segue: UIStoryboadSegue, sender: AnyObject?){
if segue.identifier == "whatever you put in storyboard for segue id" {
if let inserWorkoutVC = segue.destinationViewController as? InsertWorkout {
//pass the data here but don't attempt to update your destination's view ui!!,
}
}
}
}

Resources