Swift, как делиться жестами между перекрывающимися видами - PullRequest
0 голосов
/ 22 сентября 2018

Я создал два набора коллекций, перекрывающихся в одном контроллере.Я хочу, чтобы только одно горизонтальное перемещение применялось к двум представлениям коллекции одновременно.На данный момент только топпер распознает этот жест.На самом деле, я даже не знаю, будет ли это хорошо (применить один жест на два представления коллекции одновременно) хорошо.

1) Я хочу знать, возможно ли это 2) и если это возможно, то как это сделать.

Я использую Xcode 9.4.1, swift4.

Это мой код.

просмотр контроллера

import UIKit
import JTAppleCalendar
import SideMenu

class ViewController: UIViewController,UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
    let formatter = DateFormatter()

    var startDate = Date()

    @IBOutlet var mainView: UIView!
    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var collectionView: JTAppleCalendarView!
    @IBOutlet var navigationItemBar: UINavigationItem!

    @IBOutlet var someCollectionnView: UICollectionView!

    let reuseIdentifier = "someCell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]


    // MARK: - UICollectionViewDataSource protocol

    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

        cell.someLabel.text = items[indexPath.item];
        // Use the outlet in our custom class to get a reference to the UILabel in the cell

        return cell
    }

    override func viewDidLoad(){
        super.viewDidLoad()
        self.edgesForExtendedLayout = []

        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 3.0

        collectionView.scrollToDate(Date(), animateScroll: false)


        setupCalendarView()


        SideMenuManager.default.menuWidth = round((UIScreen.main.bounds.width) * 0.25)


        let clickGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(gesture:)))
        collectionView.addGestureRecognizer(clickGesture)



        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }

        someCollectionnView.isScrollEnabled = true



    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return mainView
    }

    @objc func longPressed(gesture: UILongPressGestureRecognizer){
        let point = gesture.location(in: gesture.view!)
        if gesture.state == .ended {
            if let cellState = collectionView.cellStatus(at: point) {
                startDate = cellState.date
                self.performSegue(withIdentifier: "MonthToWeekSegue", sender: self)
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? WeekViewController {
            vc.startDate = startDate
        }
    }

    func setupCalendarView(){
        //Setup calendar spacing
        collectionView.minimumLineSpacing = 0
        collectionView.minimumInteritemSpacing = 0

        //Setup labels
        collectionView.visibleDates { (visibleDates) in
            self.setupViewsOnCalendar(from: visibleDates)
        }

        collectionView.scrollDirection = .horizontal
    }

    func setupViewsOnCalendar(from visibleDates: DateSegmentInfo){
        let date = visibleDates.monthDates.first!.date

        self.formatter.dateFormat = "MM"
        self.navigationItemBar.title = self.formatter.string(from:date)

    }

    func handleCellTextColor(view: JTAppleCell?, cellState: CellState){
        guard let validCell = view as? CustomCell else { return }
        if cellState.dateBelongsTo == .thisMonth {
            validCell.dateLabel.textColor = UIColor.black
        } else {
            validCell.dateLabel.textColor = UIColor.gray
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension ViewController: JTAppleCalendarViewDataSource {

    func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
        formatter.dateFormat="yyyy MM dd"
        formatter.timeZone=Calendar.current.timeZone
        formatter.locale = Calendar.current.locale

        let startDate = formatter.date(from: "2015 01 01")!
        let endDate = formatter.date(from: "2030 12 31")!

        let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
        return parameters
    }
}

extension ViewController: JTAppleCalendarViewDelegate {
    //display the cell
    func calendar(_ calendar: JTAppleCalendarView, willDisplay cell: JTAppleCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
        let mycell = cell as! CustomCell
        mycell.dateLabel.text = cellState.text

        handleCellTextColor(view: mycell, cellState: cellState)

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy'-'MM'-'dd"
        let someDate = formatter.date(from: "2018-12-29")!
        if cellState.date < someDate {
            for holiday in holidayArray {
                if holiday.date == cellState.date && holiday.category == "holiday" && cellState.dateBelongsTo == .thisMonth {
                    mycell.detailLabel.text = holiday.name
                    mycell.dateLabel.textColor = UIColor.red
                    break;
                } else{
                    mycell.detailLabel.text = ""
                    mycell.detailLabel.textColor = UIColor.black
                }
            }
        } else {
            for holiday in holidayArray_2019 {
                if holiday.date == cellState.date && cellState.dateBelongsTo == .thisMonth {
                    mycell.detailLabel.text = holiday.name
                    mycell.dateLabel.textColor = UIColor.red
                    break;
                } else{
                    mycell.detailLabel.text = ""
                    mycell.detailLabel.textColor = UIColor.black
                }
            }

        }

        formatter.dateFormat = "yyy MM dd" // or whatever format you want.

        let currentDateString = formatter.string(from: Date())
        let cellStateDateString = formatter.string(from: cellState.date)

        if currentDateString ==  cellStateDateString && cellState.dateBelongsTo == .thisMonth {
            // this
            mycell.backgroundColor = UIColor.red
        } else {
            // that
            mycell.backgroundColor = UIColor.white
        }

    }

    func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
        let mycell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

        mycell.dateLabel.text = cellState.text
        mycell.layer.borderColor = UIColor.black.cgColor
        mycell.layer.borderWidth = 1

        self.calendar(calendar, willDisplay: mycell, forItemAt: date, cellState: cellState, indexPath: indexPath)
        return mycell
    }

    func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
        setupCalendarView()
    }

}

extension UIColor {
    convenience init(colorWithHexValue value: Int, alpha: CGFloat = 1.0) {
        self.init(
            red : CGFloat((value & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((value & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(value & 0x0000FF) / 255.0,
            alpha: alpha
        )
    }
}

раскадровка

enter image description here

симулятор enter image description here

Спасибо.

...