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

标签 ios swift xcode collections

我想自动选择中间单元格。如果我选择开始时间结束时间,就像截图一样,这里我选择01:00作为< strong>开始时间 和 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
    } 
}

最佳答案

创建以下全局属性:

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

        }

    }
}

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

希望对你有用!

关于ios - 在 CollectionView 中自动选择中间单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275402/

相关文章:

ios - 如何使用 iOS 13 在 iOS 设备中获取 SSID

ios - (Xcode 12/iOS 14) 如何解决调用 App.Alert 和 SwiftUI.Alert 时出现的兼容性错误?

ios - 数组计数(数组内)以确定 UIView 宽度

ios - Swift/Xcode - 向 UITextField 添加货币符号和逗号

Xcode 4 Instruments 不显示源代码行

iPhone 键盘隐藏 UISeachBar

ios - Swift:尝试旋转绘制的形状?

ios - Swift 中 @discardableResult 声明的 ObjC 版本是什么

ios - "libRestKit.a, file was built for archive which is not the architecture being linked (armv7)"

ios - 为什么纬度和经度在 ios 9 中显示为零?