从Swift中的另一个视图控制器访问表视图单元信息

时间:2018-05-12 20:45:08

标签: ios swift xcode uitableview

我们正在设计一个应用程序,我们有一个表视图控制器和一个视图控制器。在我的选项卡视图控制器中,它在每个单元格中都有按钮,我们将其拖动以使其与视图控制器单元格建立连接。如果我们点击不同单元格中的按钮,我们想要从coredata更新视图控制器中的数据。(每个按钮转到不同的人信息)但问题是我们无法从视图控制器类访问有关单元格的信息。我们在这里找到了一些例子,但我们做不到。

     //table view controller class
            var charArray = ["a","b","c"]
             override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
                    let myCharacter = charArray[indexPath.row]
                    cell.textLabel?.font = UIFont(name: "HoeflerText-Italic", size: 27.0)
                    cell.textLabel?.text = myCharacter

                    return cell
                }


        //view controller class
         override func viewDidLoad() {
                super.viewDidLoad()
                charText.isEditable = false
                guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                    return
                }
                let managedContext = appDelegate.persistentContainer.viewContext// This one is created to work with Managed Object
                let entity = NSEntityDescription.entity(forEntityName: "CHARACTER",in: managedContext)!


            if let a = CI.tableView.cellForRow(at: IndexPath.init(row: i, section: i)),a.textLabel?.text == "Iron Man"{
                    imageChar.image =  UIImage(named: "Iron_Man")
                    btn1.setTitle("Iron Man ", for: .normal)
                    btn1.showsTouchWhenHighlighted = true
                    btn2.setTitle("Iron Man 2", for: .normal)
                    btn2.showsTouchWhenHighlighted = true
                    btn3.setTitle("Iron Man 3", for: .normal)
                    btn3.showsTouchWhenHighlighted = true

                let person = NSManagedObject(entity: entity,insertInto: managedContext)
                        person.setValue(CHS[0].species , forKeyPath: "species")
                        person.setValue(CHS[0].name , forKeyPath: "title")
                        person.setValue(CHS[0].gender, forKeyPath: "gender")
                        person.setValue(CHS[0].textInfo, forKey: "information")
                        person.setValue(CHS[0].age, forKey: "age")

                        do {// Save into our app's dedicated disk area
                            try managedContext.save()
                            people.append(person)
                        } catch let error as NSError {
                            print("Could not save. \(error), \(error.userInfo)")
                        }

              //  print(people.first as Any)

                        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CHARACTER")
                        do{
                            let request = try managedContext.fetch(fetchRequest)


                            for data in request{
                                labelName.text = data.value(forKey: "title") as? String
                                labelSpecies.text = data.value(forKey: "species") as? String
                                labelGender.text = data.value(forKey: "gender") as? String
                                charText.text = data.value(forKey: "information") as? String
                                labelAge.text = data.value(forKey: "age") as? String
                            }
                        }
                        catch let error as NSError {
                            print("Could not fetch. \(error), \(error.userInfo)")
                        }
                }



//Another option --------
        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

                let StoryBoard = UIStoryboard(name: "Main", bundle: nil)
                let CIVC = StoryBoard.instantiateViewController(withIdentifier: "CharacterInformationViewController") as! CharacterInformationViewController

                guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                    return
                }
                let managedContext = appDelegate.persistentContainer.viewContext// This one is created to work with Managed Object
                let entity = NSEntityDescription.entity(forEntityName: "CHARACTER",in: managedContext)!
                let person = NSManagedObject(entity: entity,insertInto: managedContext)
                person.setValue(CHS[indexPath.row].species , forKeyPath: "species")
                person.setValue(CHS[indexPath.row].name , forKeyPath: "title")
                person.setValue(CHS[indexPath.row].gender, forKeyPath: "gender")
                person.setValue(CHS[indexPath.row].textInfo, forKey: "information")
                person.setValue(CHS[indexPath.row].age, forKey: "age")

                do {// Save into our app's dedicated disk area
                    try managedContext.save()

                    people.append(person)
                    print(person)
                } catch let error as NSError {
                    print("Could not save. \(error), \(error.userInfo)")
                }



                let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CHARACTER")
                do{
                    let request = try managedContext.fetch(fetchRequest)

                    //Try to get data from table view controller class and make an object of my view controller class
                    for data in request{
                        CIVC.getName = (data.value(forKey: "title") as? String)!
                        CIVC.getSpecies = (data.value(forKey: "species") as? String)!
                        CIVC.getGender = (data.value(forKey: "gender") as? String)!
                        CIVC.getText = (data.value(forKey: "information") as? String)!
                        CIVC.getAge = (data.value(forKey: "age") as? String)!
                    }
                }
                catch let error as NSError {
                    print("Could not fetch. \(error), \(error.userInfo)")
                }


            }

1 个答案:

答案 0 :(得分:1)

如果您的数据集没有更改,这意味着您没有删除行,此问题的常见方法是使用单元格内每个按钮的tag属性。你可以这样设置标签:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
            let myCharacter = charArray[indexPath.row]
            cell.textLabel?.font = UIFont(name: "HoeflerText-Italic", size: 27.0)
            cell.textLabel?.text = myCharacter

            cell.btn1.tag = indexPath.row // set tag

            return cell
        }

然后您将此标记属性用作数据源的索引:

@objc func didTapButton(sender: UIButton) {
    let cellIndex = sender.tag
    let info = charArray[cellIndex]
    // do something with info
}

另一种方法是在自定义UITableViewCell中创建委托,并在每个单元格出列时设置它。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // ...
    cell.delegate = self;
    // ...
  }

每次在单元格内点击按钮时,让它在其委托(UIViewController)中调用一个方法(您在协议中定义)。该方法可以包含您想要的任何内容,包括可识别的数据。确保UIViewController符合此协议。