OGeek|极客世界-中国程序员成长平台

标题: ios - 单元格不能选择在主视图中嵌入 UItableView? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:50
标题: ios - 单元格不能选择在主视图中嵌入 UItableView?

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

注意:在属性检查器中 选择应该设置为单选吗?

更新说明: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 ")

       }
}



Best Answer-推荐答案


在这个答案中,我假设 didSelectRowAtIndexPath 正在触发。

在您的 didSelectRowAtIndexPath 中,您需要将您创建的 segue 从单元格触发到第二个 View Controller :

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

}

我不确定您使用的是哪个版本的 Swift,因此您可能需要进行一些细微的更改。

关于ios - 单元格不能选择在主视图中嵌入 UItableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40051131/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4