在CollectionView中自动选择中间单元格

时间:2018-01-16 06:43:02

标签: ios swift xcode collections

我想自动选择中间单元格 。如果我选择开始时间结束时间,就像屏幕截图那样,我选择01:00 开始时间 06:00 结束时间。我想选择自动选择时间 02:00,03:00,04:00,05:00 ,这是示例......

也许我的客户想要选择 01:00作为开始时间 21:00 作为结束时间自动< / strong>应始终选择

我有三个时间范围,我需要为工作每个范围时间显示不同时间 我有三个价格。例如:

第一次和价格早晨

第二次和价格

第三次和价格晚上

enter image description here

我可以做,怎么做?也许有框架这将帮助我做到这一点快速

我的代码在这里:

class BookingViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var bookingHall: Halls?

    var timeIntervalArray: [String] = []
    var timeIntervalArrayTwo: [String] = []
    var timeIntervalArrayThree: [String] = []
    var selectedTimeIntervalArray: [String] = []

    var bookingAmountOfHallArray: [Int] = []
    var sumOfBookingAmount: Int = 0

    var allArrayTimesAndPrices: [(time: String, price: Int)] = [] // ARRAY FOR COLLECT ALL TIMES AND ALL PRICES

    lazy var timeFormatter: DateFormatter = {

        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter

    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        configureSelectedDateAndTime()

        collectionView.allowsMultipleSelection = true 
        // MORNING TIME RANGE
        if let timeRange = generateTimeRange() {

            self.timeIntervalArray = timeRange
            self.collectionView.reloadData()

        } else {
            // Handle error
        }
        // DAY TIME RANGE
        if let timeRangeTwo = generateTimeRangeTwo() {

            self.timeIntervalArrayTwo = timeRangeTwo
            self.collectionView.reloadData()

        } else {
            // Handle error
        }
        // EVENING TIME RANGE
        if let timeRangeThree = generateTimeRangeThree() {

            self.timeIntervalArrayThree = timeRangeThree
            self.collectionView.reloadData()

        } else {
            // Handle error
        }

        if let hall = bookingHall {

            allArrayTimesAndPrices =
                timeIntervalArray.map({ (time: $0, price: hall.price) }) +
            timeIntervalArrayTwo.map({ (time: $0, price: hall.priceSecond) }) +
            timeIntervalArrayThree.map({ (time: $0, price: hall.priceThird) })

        }

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return allArrayTimesAndPrices.count

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeCell", for: indexPath) as! BookingTimeCell

        cell.timeLabel.text = allArrayTimesAndPrices[indexPath.item].time
        cell.priceLabel.text = "\(allArrayTimesAndPrices[indexPath.item].price) руб."

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let selectedCell = collectionView.cellForItem(at: indexPath)

        selectedIndexesAndBackgroundColor(cell: selectedCell!, indexPath: inde xPath)

    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

        let deselectedCell = collectionView.cellForItem(at: indexPath)

        deselectedIndexesAndBackgroundColor(cell: deselectedCell!, indexPath: indexPath)

    }
    // the selected time
    func selectedIndexesAndBackgroundColor(cell: UICollectionViewCell, indexPath: IndexPath) {

        let timeToAdd = allArrayTimesAndPrices[indexPath.item].time
        selectedTimeIntervalArray.append(timeToAdd)

    }
    // cancelled time
    func deselectedIndexesAndBackgroundColor(cell: UICollectionViewCell, indexPath: IndexPath) {

        let timeToRemove = allArrayTimesAndPrices[indexPath.item].time
        let indexTime = selectedTimeIntervalArray.index(of: timeToRemove)
        selectedTimeIntervalArray.remove(at: indexTime!)

    }
    // MORNING
    func generateTimeRange() -> [String]? {

        var result = [String]()

        if let hall = bookingHall {

            guard var startTime = timeFormatter.date(from: hall.firstStartTimeToIncreasePrice) else { return nil }
            guard let endTime = timeFormatter.date(from: hall.firstEndTimeToIncreasePrice) else { return nil }

            while startTime <= endTime {

                result.append(timeFormatter.string(from: startTime))

                startTime = Calendar.current.date(byAdding: .hour, value: 1, to: startTime)!

            }

        }

        return result
    }
    // DAY
    func generateTimeRangeTwo() -> [String]? {

        var result = [String]()

        if let hall = bookingHall {

            guard var startTime = timeFormatter.date(from: hall.secondStartTimeToIncreasePrice) else { return nil }
            guard let endTime = timeFormatter.date(from: hall.secondEndTimeToIncreasePrice) else { return nil }

            while startTime <= endTime {

                result.append(timeFormatter.string(from: startTime))

                startTime = Calendar.current.date(byAdding: .hour, value: 1, to: startTime)!

            }

        }

        return result
    }
    // EVENING
    func generateTimeRangeThree() -> [String]? {

        var result = [String]()

        if let hall = bookingHall {

            guard var startTime = timeFormatter.date(from: hall.thirdStartTimeToIncreasePrice) else { return nil }
            guard let endTime = timeFormatter.date(from: hall.thirdEndTimeToIncreasePrice) else { return nil }

            while startTime <= endTime {

                result.append(timeFormatter.string(from: startTime))

                startTime = Calendar.current.date(byAdding: .hour, value: 1, to: startTime)!

            }

        }

        return result
    } 
}

3 个答案:

答案 0 :(得分:1)

为indexPaths提供两个全局对象

var selectedRowOne:IndexPath? <br>
var selectedRowTwo:Indexpath?

之后在didSelectItemAt

   if selectedRowOne == nil {
        // Start of range is empty !!

        selectedRowOne = indexPath;
        // Logic for select the row
    } else if selectedRowTwo == nil {
        // End of range is empty
        selectedRowTwo = indexPath

        var indexPathToBeSelected :[IndexPath] = []

        for i in selectedRowOne!.row  ..< selectedRowTwo!.row {
            indexPathToBeSelected.append(IndexPath(item: i, section: 0))
        }

        // Select indexPathToBeSelected logic
    }

由于您的代码太混乱,我无法为一个案例编写代码。所以现在您必须管理一个案例,其中选择了selectedRowOneselectedRowTwo并且用户点击任何单元格。

然后您必须检查选择indexpath.row <selectedRowOne.row然后selectedRowOne = indexpath

其次else if indexpath.row > selectedRowOne.row && indexpath.row < selectedRowTwo.row然后selectedRowOne = indexpath

并且在最后条件

else if indexpath.row > selectedRowTwo.row 然后selectedRowTwo = indexpath

然后在selectedRowOneselectedRowTwo

之间应用单元格选择逻辑 如果选择了两个单元格,如果我取消选择第一个或第二个单元格,则需要正确管理selectedRowOneselectedRowTwo

希望它对你有所帮助

答案 1 :(得分:1)

在全局属性下创建:

var selectedIndexPath:IndexPath! // store selected indexpath

var arrSelectedIndexPath = [IndexPath]() // array of selected indexpath

之后

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return timeArray.count
}

// -------------------------------------------------------------------------------------------

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (self.view.frame.size.width - 60) / 7, height: (self.view.frame.size.width - 60) / 7)
}

// -------------------------------------------------------------------------------------------

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // dequeue cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

    // assign text to label
    cell.lblTitle.text = self.timeArray[indexPath.item]

    if self.arrSelectedIndexPath.contains(indexPath) {// if arrSelectedIndexPath contain indexpath then change backgrond color of label

        cell.lblTitle.backgroundColor = UIColor(red: 81.0/255.0, green: 182.0/255.0, blue: 186.0/255.0, alpha: 1.0)

    }else { // else set it to default color white

        cell.lblTitle.backgroundColor = UIColor.white

    }

    // return collection view cell
    return cell
}

// -------------------------------------------------------------------------------------------

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if self.selectedIndexPath == nil { // if selected indexpath nil then assign first indexpath

        self.selectedIndexPath = indexPath
        self.arrSelectedIndexPath.removeAll() // remove all items from array
        self.collectionView.reloadData() // reload CollectionView

    }else {

        if self.arrSelectedIndexPath.count == 0 { // if arrSelectedIndexPath.count == 0 then

            if self.selectedIndexPath.item < indexPath.item { // check first selected indexpath is smaller then end indexpath

                // fill all intermediate cell
                for i in self.selectedIndexPath.item...indexPath.item {
                    self.arrSelectedIndexPath.append(NSIndexPath(item: i, section: 0) as IndexPath)
                }

                // reload collection view and update background color
                self.collectionView.reloadData()

                // reset first selected indexpath
                self.selectedIndexPath = nil

            }else { // else select first selected indexpath

                self.selectedIndexPath = indexPath

            }

        }else { // else remove all items from

            self.arrSelectedIndexPath.removeAll()
            self.collectionView.reloadData()
            self.selectedIndexPath = indexPath

        }

    }
}

// -------------------------------------------------------------------------------------------

}

希望它适合你!

答案 2 :(得分:0)

创建一个属性来存储selectedIndexPath var selectedItem: IndexPath?, 然后为第一个选定的项目分配它的值。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    guard let selectedItem = selectedItem else{
        selectedItem = indexPath
        return
    }

    //loop for selecting items between current selected item and previous selected item.
    for i in selectedItem.row...indexPath.row {
         let selectedCell = collectionView.cellForItem(at: IndexPath(row: i, section: indexPath.section))
         selectedIndexesAndBackgroundColor(cell: selectedCell!, indexPath: inde xPath)
    }        

}

并在didDeSelectItemAt中执行相同操作,以便相应地取消选择项目。