Добавление представления в calendarTableView пользовательских ячеек сломало код Swift 4 - PullRequest
0 голосов
/ 18 октября 2019

Я создал calendarTableVIew с пользовательскими ячейками. В ячейках было только dayLabel, и для представления содержимого я назначил границу, чтобы просто очертить ячейку и цвет фона. Решив, что мне нужно пространство между ячейками, я добавил dayView, который теперь имеет границу для контура, и dayLabel в нем. calendarTableview имеет границы ячейки текущего дня в другом цвете. Проблема в том, что, поскольку я добавил новую dayView в ячейки, эта ячейка текущего дня, а также любая выбранная ячейка, когда вы выбираете любой день, теперь имеют черную рамку, и didDeselect не отображает t change it to default anymore. I tried to give просмотр ( contentView ) a rounded outline to see what effects it would produce and I can indeed see the rounded view , the dayView border, and the dayLabel`параметры все затронуты. Вы видите, откуда этот черный прямоугольник? Я не могу найти это. Как всегда, большое спасибо за ваше время и помощь.

Вот ячейка:

enter image description here enter image description here

и это код (закомментированные части - это код перед добавлением нового представления):

Пользовательская ячейка:

class CalendarTableViewCell: UITableViewCell {


    @IBOutlet weak var view: UIView! // added after errror has began but didn't solve it
    @IBOutlet weak var dayView: UIView!
    @IBOutlet weak var dayLabel: UILabel!


    var cellDate : String!
    var cellId: String!
    var cellWeekday: Int!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        configureUi()
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        // Set your default background color, title color etc
        configureUi()
    }
    func configureUi() {
        self.backgroundColor = UIColor.red
        self.isOpaque = false
        view.layer.cornerRadius = 5
        view.layer.borderWidth = 0
        view.clipsToBounds = true
        dayView.layer.cornerRadius = 5
        dayView.layer.borderWidth = 2
        dayView.clipsToBounds = true
        if Theme.selectedTheme == 1 {
            if #available(iOS 11.0, *) {
               view.layer.backgroundColor = UIColor.clear.cgColor//Theme.textFieldBackgroundColor?.cgColor//backgroundColor?.cgColor
                view.layer.borderColor = UIColor.purple.cgColor
                dayView.layer.backgroundColor = Theme.textFieldBackgroundColor?.cgColor
                dayView.layer.borderColor = Theme.secondTintColor?.cgColor

                dayLabel.layer.backgroundColor = Theme.textFieldBackgroundColor?.cgColor//labelBackgroundColor?.cgColor
                dayLabel.textColor = Theme.textFieldTextColor//labelTextColor
            } else {
                // Fallback on earlier versions
                layer.backgroundColor = Theme.textFieldBackgroundColorRgb.cgColor//backgroundColorRgb.cgColor

                dayView.layer.backgroundColor = Theme.textFieldBackgroundColorRgb.cgColor//backgroundColorRgb.cgColor
                dayView.layer.borderColor = Theme.secondTintColorRgb.cgColor//calendarCellRgb.cgColor

                dayLabel.layer.backgroundColor = Theme.textFieldBackgroundColorRgb.cgColor//labelBackgroundColorRgb.cgColor
                dayLabel.textColor = Theme.textFieldTextColorRgb//labelTextColorRgb
            }
        } else if Theme.selectedTheme == 2 {
            if #available(iOS 11.0, *) {
                layer.borderColor = Theme.calendarCell2?.cgColor
                layer.backgroundColor = Theme.backgroundColor2?.cgColor
                dayLabel.layer.backgroundColor = Theme.labelBackgroundColor2?.cgColor
                dayLabel.textColor = Theme.labelTextColor2
            } else {
                // Fallback on earlier versions
                layer.borderColor = Theme.calendarCellRgb2.cgColor
                layer.backgroundColor = Theme.backgroundColorRgb2.cgColor
                dayLabel.layer.backgroundColor = Theme.labelBackgroundColorRgb2.cgColor
                dayLabel.textColor = Theme.labelTextColorRgb2
            }
        }
    }

//    func configureUi() {
//        layer.cornerRadius = 5
//        layer.borderWidth = 2
//        clipsToBounds = true
//        if Theme.selectedTheme == 1 {
//            if #available(iOS 11.0, *) {
//                layer.borderColor = Theme.calendarCell?.cgColor
//                layer.backgroundColor = Theme.backgroundColor?.cgColor
//                dayLabel.layer.backgroundColor = Theme.labelBackgroundColor?.cgColor
//                dayLabel.textColor = Theme.labelTextColor
//            } else {
//                // Fallback on earlier versions
//                layer.borderColor = Theme.calendarCellRgb.cgColor
//                layer.backgroundColor = Theme.backgroundColorRgb.cgColor
//                dayLabel.layer.backgroundColor = Theme.labelBackgroundColorRgb.cgColor
//                dayLabel.textColor = Theme.labelTextColorRgb
//            }
//        } else if Theme.selectedTheme == 2 {
//            if #available(iOS 11.0, *) {
//                layer.borderColor = Theme.calendarCell2?.cgColor
//                layer.backgroundColor = Theme.backgroundColor2?.cgColor
//                dayLabel.layer.backgroundColor = Theme.labelBackgroundColor2?.cgColor
//                dayLabel.textColor = Theme.labelTextColor2
//            } else {
//                // Fallback on earlier versions
//                layer.borderColor = Theme.calendarCellRgb2.cgColor
//                layer.backgroundColor = Theme.backgroundColorRgb2.cgColor
//                dayLabel.layer.backgroundColor = Theme.labelBackgroundColorRgb2.cgColor
//                dayLabel.textColor = Theme.labelTextColorRgb2
//            }
//        }
//    }

}

Просмотр таблицы:

extension WorkshopBookingsViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell
//        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell
        cell.configureUi()
        let date = datesArray[indexPath.row]
        cell.cellDate = String( describing: date)
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let dayInWeek = dateFormatter.string(from: date)
//        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + "\(dayNamesArray[components.weekday! - 1])"
        cell.dayLabel.text = "\(String(describing: components.day!))" + " " + dayInWeek
        cell.cellWeekday = components.weekday!
        //        print("cell weekday is: \(cell.cellWeekday!)") // prints correct weekday
        cell.cellId = "\(String(format:"%04d", components.year!))" + "\(String(format:"%02d", components.month!))" + "\(String(format:"%02d", components.day!))"
        self.selectedDate = cell.cellId // used for time slots cellId
        //        print("##################### selectedDate in tableview is :\(self.selectedDate) ")
        // highlighting current day cell
        if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {

            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {

                    cell.dayLabel.backgroundColor = UIColor.blue
                    cell.dayLabel.layer.borderColor = UIColor.purple.cgColor
//                    cell.contentView.backgroundColor = UIColor.blue
                    cell.dayView.layer.borderColor = UIColor.blue.cgColor//Theme.firstTintColor?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.dayView.layer.borderColor = Theme.firstTintColorRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {
                    cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                }
            }
            //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
            self.selectedDate = cell.cellId
            self.updateTimeSlots(selectedCell: cell)
        }
//        if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
//
//            cell.layer.borderWidth = 4
//            if Theme.selectedTheme == 1 {
//                if #available(iOS 11.0, *) {
//                    cell.layer.borderColor = Theme.calendarCellToday?.cgColor
//                } else {
//                    // Fallback on earlier versions
//                    cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
//                }
//
//            } else if Theme.selectedTheme == 2 {
//                if #available(iOS 11.0, *) {
//                    cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
//                } else {
//                    // Fallback on earlier versions
//                    cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
//                }
//            }
//            //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
//            self.selectedDate = cell.cellId
//            self.updateTimeSlots(selectedCell: cell)
//        }
        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.configureUi()
            // highlighting current day cell
            if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
                cell.dayView.layer.borderWidth = 4
                if Theme.selectedTheme == 1 {
                    if #available(iOS 11.0, *) {
                        cell.dayView.layer.borderColor = Theme.firstTintColor?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.dayView.layer.borderColor = Theme.firstTintColorRgb.cgColor
                    }
                } else if Theme.selectedTheme == 2 {
                    if #available(iOS 11.0, *) {
                        cell.dayView.layer.borderColor = Theme.calendarCellToday2?.cgColor
                    } else {
                        // Fallback on earlier versions
                        cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
                    }
                }
                //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")

                self.selectedDate = cell.cellId
            }
        }


//        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
//            cell.configureUi()
//            // highlighting current day cell
//            if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
//                cell.layer.borderWidth = 4
//                if Theme.selectedTheme == 1 {
//                    if #available(iOS 11.0, *) {
//                        cell.layer.borderColor = Theme.calendarCellToday?.cgColor
//                    } else {
//                        // Fallback on earlier versions
//                        cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
//                    }
//                } else if Theme.selectedTheme == 2 {
//                    if #available(iOS 11.0, *) {
//                        cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
//                    } else {
//                        // Fallback on earlier versions
//                        cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
//                    }
//                }
//                //            print(" @@@@@@@@@@@@@@@@@@@@@@@@@@   selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
//
//                self.selectedDate = cell.cellId
//            }
//        }
    }



    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
            cell.layer.borderWidth = 4
            if Theme.selectedTheme == 1 {
                if #available(iOS 11.0, *) {
                    cell.dayView.layer.borderColor = Theme.backgroundColor?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.dayView.layer.borderColor = Theme.firstTintColorRgb.cgColor
                }

            } else if Theme.selectedTheme == 2 {
                if #available(iOS 11.0, *) {

                    cell.dayView.layer.borderColor = Theme.firstTintColor2?.cgColor
                } else {
                    // Fallback on earlier versions
                    cell.dayView.layer.borderColor = Theme.firstTintColorRgb2.cgColor
                }
            }
            self.updateTimeSlots(selectedCell: cell)
        }

//        if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
//            cell.layer.borderWidth = 4
//            if Theme.selectedTheme == 1 {
//                if #available(iOS 11.0, *) {
//                    cell.layer.borderColor = Theme.firstTintColor?.cgColor
//                } else {
//                    // Fallback on earlier versions
//                    cell.layer.borderColor = Theme.firstTintColorRgb.cgColor
//                }
//
//            } else if Theme.selectedTheme == 2 {
//                if #available(iOS 11.0, *) {
//
//                    cell.layer.borderColor = Theme.firstTintColor2?.cgColor
//                } else {
//                    // Fallback on earlier versions
//                    cell.layer.borderColor = Theme.firstTintColorRgb2.cgColor
//                }
//            }
//            self.updateTimeSlots(selectedCell: cell)
//        }
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { // Error: this causes multiple index paths to be dequeed at tableview reload. call directly in cellForRowAt instead
//        let cell: CalendarTableViewCell = tableView(self.calendarTableview, cellForRowAt: IndexPath.init(row: self.actualDay - 1, section: 0)) as! CalendarTableViewCell
//        self.updateTimeSlots(selectedCell: cell)

    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //        print("scrollViewDidEndDecelerating")
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            //            print("scrollViewDidEndDragging")
        }
    }

    func scrollingFinish() -> Void {
        //        print("Scroll Finished!")

    }


}

1 Ответ

0 голосов
/ 18 октября 2019

Нашел проблему. Поскольку я добавил новый dayView вид, я указал self.backgroundColor для самой ячейки, но я должен был также указать self.layer.borderColor = UIColor.clear.cgColor, иначе он получит черный цвет по умолчанию.

Слой этой ячейки получаетя иногда все еще. Итак, в моих пользовательских ячейках слои:

self (сама ячейка) contentView добавил метку вида

И вы должны указать backgroundColor и borderColor для каждого слоя. Надеюсь, что это будет полезно для других. Приветствия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...