iOS- UICollectionView горизонтальная прокрутка каждой ячейки в UITableView

#ios #swift #uitableview #uicollectionview

#iOS #swift #uitableview #uicollectionview

Вопрос:

У меня есть UITableView, в который я поместил UICollectionView, а затем повторно использовал этот сценарий для 10 или более ячеек.

Я хочу, чтобы при прокрутке моего UICollectionView каждая из ячеек другого представления коллекции также прокручивалась одновременно синхронно.

MyViewController.swift

 import UIKit


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {    
    
    @IBOutlet private weak var menuButton: UIButton!
    @IBOutlet var dottedView: UIView!
    
    var array1 = ["Indian Standard Time","Adelaide Standard Time"
        ,"Auckland Standard Time","Melbourne Standard Time",
         "Manchester Standard Time","Paris Standard Time",
         "Alaska Standard Time","Greenland Standard Time"
        ,"Sutherland Standard Time","Russia Standard Time"]
    
    var array2 = ["desc","desc","desc","desc","desc"]
    
    var array3 = ["Mon","Tue","Wed","Thu", "Fri","Sat","Sun"]
    
    var array4 = ["12 2021","12 2021","12 2021","12 2021", "12 2021","12 2021","12 2021"]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    @IBOutlet var maintableview: UITableView!
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! TableViewCell
        cell.tag = indexPath.row
        cell.collectionview.tag = (100 * indexPath.section)   indexPath.row
        cell.label1.text = array1[indexPath.row]
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
    
    @IBAction func datetimeclick(_ sender: Any) {
        let vc = storyboard?.instantiateViewController(identifier: "dateViewController") as! DateViewController
        present(vc, animated: true)
    }
    
    @IBAction func addbtnclick(_ sender: Any) {
        let vc = storyboard?.instantiateViewController(identifier: "timezonecontroller") as! TimeZoneViewController
        present(vc, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.dottedView.addDashedBorder()
        
        let nextdate  = Date().addDate()
        let prevdate  = Date().subtractDate()
        let dayofweek = String().dayOfWeek(fDate: nextdate)
        let tomorrowDate = String().dateOfWeek(fDate: nextdate)
        let yesterdayDate = String().dateOfWeek(fDate: prevdate)
        let year  = String().getYear(fDate: Date())
        let splitstr = dayofweek?.prefix(3)
        
        print("tomdate",tomorrowDate!)
        print("prevdate",yesterdayDate!)
        print("year",year!)
        print("dayofWeekCap", splitstr!)
        
        menuButton.isUserInteractionEnabled = true
        let interaction  = UIContextMenuInteraction(delegate :self)
        menuButton.backgroundColor = UIColor(hexString: "#1361E5")
        menuButton.addInteraction(interaction)
        
    }
    
    override func viewDidLayoutSubviews() {
        
    }
}
 

MyTableViewCell.swift

 import UIKit

class TableViewCell: UITableViewCell {
    @IBOutlet weak var label1: UILabel!
    
    @IBOutlet weak var label2: UILabel!
    
    
    
    @IBOutlet weak var collectionview: UICollectionView!
    @IBOutlet weak var collectioncell: UICollectionViewCell!
    @IBOutlet weak var collectionText: UILabel!
    var scrollToPosition = 0
    var indexPosition = 0
    
extension TableViewCell : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 48
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let arrayString = timeSlot[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectioncell", for: indexPath)
        let title = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 33))
        
        indexPosition = indexPath.row
        
        if indexPath.row >= scrollToPosition
        {
            title.textColor = UIColor.white
            cell.contentView.backgroundColor = UIColor.systemBlue
        }
        else
        {
            title.textColor = UIColor.black
            cell.layer.borderWidth = 1.0
            cell.layer.borderColor = UIColor.darkGray.cgColor
            cell.contentView.backgroundColor = UIColor.white
        }
        
        title.text = arrayString
        title.textAlignment = NSTextAlignment.center
        for subView in cell.contentView.subviews {
            subView.removeFromSuperview()
        }
        
        cell.contentView.addSubview(title)
        
        let now = Date()
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_IN")
        formatter.dateFormat = "HH:mm" //for complete format EEEE dd MMMM YYYY HH:mm
        let datetime = formatter.string(from: now)
        let currentDate = createDateFromString(string: datetime)
        
        for i in timeSlot.indices {
            let arrayDate = createDateFromString(string: timeSlot[i])
            
            if currentDate > arrayDate amp;amp; flagDate == false  {
                flagDate = true
                countToScroll = i
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 33)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        DispatchQueue.main.async {
            for cell in self.collectionview.visibleCells {
                let indexpath = self.collectionview.indexPath(for: cell)

                self.indexPosition = indexpath!.row
                self.collectionview.selectItem(at: IndexPath(row: self.indexPosition, section: 0), animated: true, scrollPosition: .centeredHorizontally)
            }
        }

    }
}
 

Комментарии:

1. Каково направление прокрутки для Collectionview?

2. Представление коллекции прокручивается по горизонтали