NinjaDeveloper NinjaDeveloper - 1 month ago 5
iOS Question

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".

enter image description here

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 ")

}
}

Answer

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.