2017-12-02 18 views
1

collectionView 내에 tableView를 배치하고 대리자를 추가했습니다. 문제는 collectionView에서 다른 tableViews의 데이터를 제어하려고한다는 것입니다.UICollectionView의 UITableView

모든 collectionView에는 현재 날짜의 이름 (예 : '월요일')의 레이블이 있습니다. 레이블 아래에 tableView가 있습니다. 테이블 뷰에서 collectionView의 인덱스를 기반으로 다른 데이터가 표시되어야합니다.

예에서 모든 tableView에는 두 개의 셀이 있습니다. collectionView의 첫 번째 항목에있는 tableView에 cell1 : "1"및 cell2 : "2"가 표시되어야하며 두 번째 항목의 tableView에는 cell1 : "3"및 cell2 : "4"가 표시되어야합니다.

import UIKit 

class StundenplanCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     myHours.append(myH0) 
     myHours.append(myH1) 
     myHours.append(myH2) 
     myHours.append(myH3) 
     myHours.append(myH4) 
     myHours.append(myH5) 

     collectionView.delegate = self 
     collectionView.dataSource = self 
    } 

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

    //MARK: Outlets 
    @IBOutlet weak var collectionView: UICollectionView! 

    //MARK: Variables 
    var myDays = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag"] 
    var myHours: [[String]] = Array() //Array that holds myH1 - myH5 
    var myH0 = ["1", "2"] 
    var myH1 = ["3", "4"] 
    var myH2 = ["5", "6"] 
    var myH3 = ["7", "8"] 
    var myH4 = ["9", "10"] 
    var myH5 = ["Error", "Error"] 

    var tableLoop = 0 

    var headerColor: UIColor = UIColor(red: CGFloat(255/255.0), green: CGFloat(140/255.0), blue: CGFloat(60/255.0), alpha: CGFloat(1.0)) 


    //MARK: Table and Collection View 
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return myDays.count 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell: StundenplanCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "stundenplanCollectionCell", for: indexPath) as! StundenplanCollectionViewCell 
     cell.titleLabel.text = myDays[indexPath.row] 
     cell.titleLabel.backgroundColor = headerColor 
     cell.titleLabel.textColor = UIColor.white 
     return cell 
    } 


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return myHours[tableLoop].count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell: StundenplanTableViewCell = tableView.dequeueReusableCell(withIdentifier: "stundenplanTableCell", for: indexPath) as! StundenplanTableViewCell 
     cell.titleLabel.text = myHours[/*Here should the indexPath.row of the collectionView item be placed*/][indexPath.row] 
     return cell 
    } 
} 

class StundenplanCollectionViewCell: UICollectionViewCell { 
    @IBOutlet weak var titleLabel: UILabel! 
    @IBOutlet weak var tableView: UITableView! 
} 

class StundenplanTableViewCell: UITableViewCell { 
    @IBOutlet weak var titleLabel: UILabel! 
} 

image 1 : 다음은 collectionView에서 처음있는 tableView (collectionView의 첫 번째 항목)를 볼 수 있습니다

image 2 : 다음 두 번째를 볼 수 있습니다 나는 현재 아래의 코드를 사용하고

collectionView에있는 tableView (collectionView의 두 번째 항목)

image 3 : 스토리 보드

image 4 : (! @missionMan에 의해 대답에 따라 - 그런데 감사) 다른

업데이트 코드

뷰에서 개체의 구조 당신은 테이블 셀에 테이블 대리자 메서드를 추가 할 수 있습니다

import UIKit 

class StundenplanCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     navigationController?.navigationBar.prefersLargeTitles = false 
     navigationController?.navigationBar.prefersLargeTitles = true 
     navigationItem.largeTitleDisplayMode = .always 

     myHours.append(myH0) 
     myHours.append(myH1) 
     myHours.append(myH2) 
     myHours.append(myH3) 
     myHours.append(myH4) 
     myHours.append(myH5) 

     collectionView.delegate = self 
     collectionView.dataSource = self 
    } 

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

    //MARK: Outlets 
    @IBOutlet weak var collectionView: UICollectionView! 

    //MARK: Variables 
    var myDays = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag"] 
    var myHours: [[String]] = Array() //Array that holds myH1 - myH5 
    var myH0 = ["1", "2"] 
    var myH1 = ["3", "4"] 
    var myH2 = ["5", "6"] 
    var myH3 = ["7", "8"] 
    var myH4 = ["9", "10"] 
    var myH5 = ["Error", "Error"] 

    var headerColor: UIColor = UIColor(red: CGFloat(255/255.0), green: CGFloat(140/255.0), blue: CGFloat(60/255.0), alpha: CGFloat(1.0)) 


    //MARK: Table and Collection View 
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return myDays.count 
    } 

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     guard let cell = tableView.dequeueReusableCell(withIdentifier: "stundenplanCollectionViewCell") as? StundenplanCollectionViewCell else { //how can I access the inner tableView? Error: Use of unresolved identifier 'tableView' 
      return UICollectionViewCell() 
     } 

     //set data and reload inner table from outer view controller (StundenplanCollectionViewController according to your code) 
     cell.dayItems = myHours[indexPath.row] 
     cell.tableView.reloadData() 
     //... 

     return cell 
    } 


class StundenplanCollectionViewCell: UICollectionViewCell { 
    @IBOutlet weak var titleLabel: UILabel! 
    @IBOutlet weak var tableView: UITableView! 
    var dayItems: [String] = [] 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     self.tableView.delegate = self // <-- set delegates inner table 
     self.tableView.dataSource = self 
    } 
} 

extension StundenplanCollectionViewCell: UITableViewDataSource, UITableViewDelegate { 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return dayItems.count 
    } 

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return 100 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell: StundenplanTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "stundenplanTableViewCell") as? StundenplanTableViewCell)! 
     //... 
     return cell 
    } 
} 

class StundenplanTableViewCell: UITableViewCell { 
    @IBOutlet weak var titleLabel: UILabel! 
} 
+2

왜 테이블보기에 두 행만있는 경우 각 셀에 표보기를 추가합니까? 콜렉션 뷰 셀에 두 개의 레이블을 직접 추가하지 않는 이유는 무엇입니까? – rmaddy

+0

디자인하려는 것을 스크린 샷으로 공유하십시오. 그 후에, 나는 너를 도울 수있다. – iDev750

+0

@rmaddy : 사용자가 행 수를 변경할 수 있기 때문에. 그것은 단지 샘플 데이터입니다. 실제로 테이블 당 11 행과 같은 것이 더 많습니다. – Adrian1304

답변

0

클래스를 선택한 다음 하루 동안 데이터를 설정할 수 있습니다. 따라서 각 콜렉션 셀에는 자체 테이블과 자체 데이터가 있습니다. StundenplanCollectionViewController

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    guard let cell = collectionView.dequeueReusableCell(withIdentifier: "stundenplanCollectionViewCell") as? StundenplanCollectionViewCell else { //<-- HERE 
     return UICollectionViewCell() 
    } 

    //set data and reload inner table from outer view controller (StundenplanCollectionViewController according to your code) 
    cell.dayItems = myH[indexPath.row] 
    cell.innerTableView.reloadData() 
    ... 

    return cell 
} 
+0

우선 : 도와 줘서 고마워! 하지만 두 번째 코드 (public func ...)를 어디에 두어야하는지 잘 모르겠습니다. 추가 정보를 제공해 주시겠습니까? "StundenplanCollectionViewController"의 "cellForItemAt"함수를 public 함수로 대체했습니다. 그러나 Xcode는 "확인되지 않은 식별자 'tableView'사용"이라고 말합니다. – Adrian1304

+0

당신을 진심으로 환영합니다. 그래, 그 대답은 조금 개선되었다. 이것이 도움이되기를 바랍니다. – missionMan

+0

그건 분명히 나를 위해 몇 가지 명확하게했다. 고마워요! 하지만 결국에는 올바른 방법으로 코드를 구현할 수 없습니다. 힌트에 따라 코드를 업데이트하고 질문에 추가 할 것입니다. 코드를 다시 살펴볼 수 있다면 좋을 것입니다.** ViewController ** (StundenplanCollectionViewController) 내에서 tableView에 액세스하는 방법을 얻지 못했습니다. – Adrian1304

0

에 collectionView의 외부 세포에서

class StundenplanCollectionViewCell: UICollectionViewCell { //<-- outer cell 
    @IBOutlet weak var titleLabel: UILabel! 
    @IBOutlet weak var innerTableView: UITableView! //<-- declare inner table 
    var dayItems: [String] = [] 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     self.innerTableView.delegate = self // <-- set delegates inner table 
     self.innerTableView.dataSource = self 
    } 
} 

extension StundenplanCollectionViewCell: UITableViewDataSource, UITableViewDelegate { 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return dayItems.count 
    } 

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     ... 
    } 

     ... 

설정 데이터 왜 당신이 UITableView에서 dequeueUICollectionViewCell하려고하는이 같은

?

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) 
    ... 
} 
+0

맞습니다. 업데이트 된 코드의 유일한 문제였습니다. 이제 작동 중입니다! 감사. – Adrian1304