Cell是不是可选择在主视图里面嵌入UItableView?

时间:2016-10-14 20:01:16

标签: ios iphone uitableview swift2 cell

我将UITableView嵌入主UIView中。我的问题是,当我单击一个单元格来选择项目时,它没有响应选择或触发segue。

注意:在属性inspecter中 选择应该设置为单一选择吗?

更新注意:prepareForSegue功能未触发或打印“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 ")

       }
}

5 个答案:

答案 0 :(得分:0)

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //self.performSegue(withIdentifier: "sites", sender: self)
        self.performSegue(withIdentifier: "CHANGE-TO-YOUT-SEGUE-ID", sender: self)
    }

是打印出来的“你好”吗?如果是这样,请从这一点开始调用你的segue。不要忘记将故事板中的segue(从左上角方块)连接为手动segue: enter image description here

答案 1 :(得分:0)

如果您的委托设置正确,请检查单元格本身的选择属性: enter image description here

答案 2 :(得分:0)

如果根本没有调用func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath),则问题是UITableView的委托未设置(或未正确设置)。代表应该是您的EditNpFormViewController

您可以通过简单地从表格中控制拖动到包含它的控制器(在故事板内)轻松设置delegate实例的UITableView。另一种简单的方法是设置

tableView.delegate = self

您只需选择故事板内的表格,然后将delegate从右侧面板的圆圈拖到控制器: enter image description here

答案 3 :(得分:0)

在这个答案中,我假设didSelectRowAtIndexPath正在解雇。

didSelectRowAtIndexPath中,您需要将您从单元格创建的segue触发到第二个视图控制器:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("selected row", indexPath)
    performSegue(with: "segueIdentifier")

}

我不确定您使用的是什么版本的Swift,因此您可能需要稍作修改。

答案 4 :(得分:0)

如果您的表视图处于编辑模式,则需要设置tableView.allowsSelectionDuringEditing = true