【问题标题】:TableView with 2 sections, Can't passing Data to Section2ViewControllerTableView 有 2 个部分,无法将数据传递给 Section2ViewController
【发布时间】:2018-11-19 18:52:57
【问题描述】:

我有一个包含 2 个部分的 TableView,每个部分都连接到另一个 ViewController,名称为 segue.identifier == "schowDetail" 的第一部分完美无缺,但第二部分:segue.identifier == "section2segue" 没有工作。我已经编写了我认为正确的代码@IBOutlet weak var textlabel: UILabel!在 Section2ViewController 中,他应该显示来自 MasterViewController prepareforsegue 的文本,但他只是在 Section2ViewController 中显示标签,我在执行中做错了吗?或者问题出在哪里。

我上传了link form MasterViewController,以及来自 Section2ViewController 的代码,来自 prepareforsegue 的代码。和来自 Main.storyboard 的 Screenshot,也许这有助于更好地解释一些事情。

class Section2ViewController: UIViewController {

@IBOutlet weak var textlabel: UILabel!

var Section1Index : Section1Index? {

    didSet {
        configureView()
    }
}
func configureView() {
    if let Section1Index = Section1Index {
        if let textlabel = textlabel {
            textlabel.text=Section1Index.name
            print("hier ist:\(Section1Index.name)")
        }
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    configureView()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail"{
  if let indexPath = tableView.indexPathForSelectedRow {
    let candy: Indications
    if isFiltering() {
      candy = filteredCandies[indexPath.row]
    } else {
      candy = indication[indexPath.row]
    }
    let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
    controller.detailIndications = candy
    controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
    controller.navigationItem.leftItemsSupplementBackButton = true
  }
}else if segue.identifier=="section2segue"{
    if let s2v=segue.destination as? Section2ViewController{
         s2v.Section1Index=sender as? Section1Index
        }
    }
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    在 masterviewcontroller 中更改它

        import UIKit
    
    class MasterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
      @IBOutlet var tableView: UITableView!
      @IBOutlet var searchFooter: SearchFooter!
    
      var detailViewController: DetailViewController? = nil
      var indication = [Indications]()
      var filteredCandies = [Indications]()
      let searchController = UISearchController(searchResultsController: nil)
    
      var section1=[Section1Index]()
    
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search"
        navigationItem.searchController = searchController
        definesPresentationContext = true
    
        searchController.searchBar.scopeButtonTitles = ["All", "Magendarmbeschwerden", "Mund- und Rachenraum", "Other"]
        searchController.searchBar.delegate = self
    
        tableView.tableHeaderView = searchFooter
    
        section1 = [
            Section1Index(name: "Was ist Ohrakupunktur", beschreibung: "Ohrakupunktur ist ..."),
            Section1Index(name: "Wie mach ich das", beschreibung: "So machen Sie das ..."),
            Section1Index(name: "was brauch ich", beschreibung: "Das brauchen Sie ...")
    
        ]
    
        indication = [
            Indications(category: "Magendarmbeschwerden", name: "Bauchschmerzen", numOfPoint: "6", indication: "Kopfschmerzen", beschreibung: "Die akute Bronchitis ist eine akute, in der Regel infektionsbedingte Entzündung der Atemwege, welche sich im Bereich der Bronchien abspielt. Bei Mitbeteiligung der Luftröhre (Trachea) spricht man von einer Tracheobronchitis.KopfschmerzenDie akute Bronchitis ist eine akute, in der Regel infektionsbedingte Entzündung der Atemwege, welche sich im Bereich der Bronchien abspielt. Bei Mitbeteiligung der Luftröhre (Trachea) spricht man von einer Tracheobronchitis.KopfschmerzenDie akute Bronchitis ist eine akute, in der Regel infektionsbedingte Entzündung der Atemwege, welche sich im Bereich der Bronchien abspielt. Bei Mitbeteiligung der Luftröhre (Trachea) spricht man von einer Tracheobronchitis.KopfschmerzenDie akute Bronchitis ist eine akute, in der Regel infektionsbedingte Entzündung der Atemwege, welche sich im Bereich der Bronchien abspielt. Bei Mitbeteiligung der Luftröhre (Trachea) spricht man von einer Tracheobronchitis.Kopfschmerzen"),
    
            Indications(category: "Endokrine", name: "Alkoholkonsum", numOfPoint: "6", indication: "Kopfschmerzen", beschreibung: "Die akute Bronchitis ist eine akute, in der Regel infektionsbedingte Entzündung der Atemwege, welche sich im Bereich der Bronchien abspielt. Bei Mitbeteiligung der Luftröhre (Trachea) spricht man von einer Tracheobronchitis.."),
          ]
    
        if let splitViewController = splitViewController {
          let controllers = splitViewController.viewControllers
          detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
        }
      }
    
      override func viewWillAppear(_ animated: Bool) {
        if splitViewController!.isCollapsed {
          if let selectionIndexPath = tableView.indexPathForSelectedRow {
            tableView.deselectRow(at: selectionIndexPath, animated: animated)
          }
        }
        super.viewWillAppear(animated)
      }
    
      override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
      }
    
      func numberOfSections(in tableView: UITableView) -> Int {
        return 2
      }
    
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return section1.count
        }else if isFiltering() {
          searchFooter.setIsFilteringToShow(filteredItemCount: filteredCandies.count, of: indication.count)
          return filteredCandies.count
        }
        searchFooter.setNotFiltering()
        return indication.count
      }
    
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellID=["Cell2","Cell"][indexPath.section]
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
        let candy: Indications
        if indexPath.section==0{
            cell.textLabel?.text=section1[indexPath.row].name
            return cell
        }else if isFiltering(){
            candy = filteredCandies[indexPath.row]
        } else {
          candy = indication[indexPath.row]
        }
        cell.textLabel!.text = candy.name
        cell.detailTextLabel!.text = candy.category
            return cell
      }
    
    
      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail"{
          if let indexPath = tableView.indexPathForSelectedRow {
            let candy: Indications
            if isFiltering() {
              candy = filteredCandies[indexPath.row]
            } else {
              candy = indication[indexPath.row]
            }
            let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            controller.detailIndications = candy
            controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            controller.navigationItem.leftItemsSupplementBackButton = true
          }
        }else if segue.identifier=="section2segue"{
            let s2v = (segue.destination as! UINavigationController).topViewController as! Section2ViewController
                let section1IndexName = sender as! UITableViewCell
            print(section1IndexName.textLabel?.text)
            s2v.section1Index = (section1IndexName.textLabel?.text)! //your sender is a UITableViewCell
            }
        }
    
    
      func filterContentForSearchText(_ searchText: String, scope: String = "All") {
        filteredCandies = indication.filter({( candy : Indications) -> Bool in
          let doesCategoryMatch = (scope == "All") || (candy.category == scope)
    
          if searchBarIsEmpty() {
            return doesCategoryMatch
          } else {
            return doesCategoryMatch && candy.name.lowercased().contains(searchText.lowercased())
          }
        })
        tableView.reloadData()
      }
    
      func searchBarIsEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
      }
    
      func isFiltering() -> Bool {
        let searchBarScopeIsFiltering = searchController.searchBar.selectedScopeButtonIndex != 0
        return searchController.isActive && (!searchBarIsEmpty() || searchBarScopeIsFiltering)
      }
    }
    extension MasterViewController: UISearchBarDelegate {
      func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
      }
    }
    
    extension MasterViewController: UISearchResultsUpdating {
      func updateSearchResults(for searchController: UISearchController) {
        let searchBar = searchController.searchBar
        let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
        filterContentForSearchText(searchController.searchBar.text!, scope: scope)
      }
    }
    

    在第 2 节中

    import UIKit
    
    class Section2ViewController: UIViewController {
    
    
        @IBOutlet weak var textlabel: UILabel!
    
        var section1Index: String? {
            didSet {
                configureView()
                print("DID SET CALLED \(section1Index)")
            }
        }
        func configureView() {
            if let section1IndexUnwrapped = section1Index {
                print("Section name is: \(section1IndexUnwrapped)")
                if let textlabel = textlabel {
                    textlabel.text = section1IndexUnwrapped
                    print("hier ist:\(section1IndexUnwrapped)")
                }
            }
        }
        override func viewDidLoad() {
            super.viewDidLoad()
            configureView()
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    }
    

    【讨论】:

    • 非常感谢您的快速回复,但还是不行,我现在真的疯了,文字标签什么都没有显示。
    • 只需像我向您展示的那样更改代码即可,请注意我更改的变量命名。我已经下载了您的代码并像上面一样对其进行了更改,并且可以正常工作
    • 当然我已经在我的项目中重新编码了你的代码,但是 Section2ViewController 只在显示屏上显示“标签”,他应该显示来自“ section1 = [ Section1Index(name: "Was ist Ohrakupunktur ", beschreibung: "Ohrakupunktur ist ...")]
    • 正确检查,因为我已经更改了两个视图控制器,第二个现在有一个刺痛而不是你的结构
    • 是的,我检查了每一个代码。我现在已经在GitHub更新了我的项目,这是更改后的新代码。你能再读一遍吗?也许我错过了什么。再次感谢您的帮助!
    【解决方案2】:
    else if segue.identifier=="section2Segue"{
                let s2v = segue.destination as! Section2ViewController
                let section1IndexName = sender as! UITableViewCell
                print(section1IndexName.textLabel?.text)
                s2v.section1Index = (section1IndexName.textLabel?.text)! 
            }
    

    将您的代码更新为此。它无法传递数据,因为它确实崩溃了

    let s2v = (segue.destination as! UINavigationController).topViewController as! Section2ViewController
    

    【讨论】:

    • 您好,非常感谢您的回复!我已经修改了这种方式,但仍然无法将数据传递给 Section2ViewController。
    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多