第一个TableView节标题不会滚动Swift 4

时间:2019-05-16 09:19:40

标签: swift uitableview core-data nsfetchedresultscontroller

我正在为我的应用构建SalesViewController,它由TableView组成,其中显示了在日期范围内找到的所有项目。 ItemOrder的子级,它具有categorydateitemIditemNameprice归因于所有{{1 }}。 我终于成功显示了String错误的itemFetchResultController,将sortDescriptor的结果正确地分成了几个部分。在配置itemFetchResultController时,我想使用从获取的category实体获得的Item属性作为填充的TableView中显示的标题部分。我的目标是,我不确定面团是否有可能或如何实现,在其部分中每个itemName仅包含1行,但知道在抓取过程中发现了很多行并将其用于显示卖价。这是我第一次使用sections,这一切都让我感到困惑。我正在尝试遵循Apple文档示例代码,这在tableView的数据源方法中给了我一些错误,如注释掉的代码所示。我在堆栈溢出处发现的所有其他帖子都非常老,而且在目标c中,所以我找不到我的疑问的答案。 到目前为止,TableView的填充正确,但是滚动时第一节标题不会移动。

是什么原因引起的? 一如既往的感谢。

这是我用于itemFetchResultController的代码:

lazy var itemFetchedResultController: NSFetchedResultsController<Item> =  {

        // first sortDescriptor filters the date range:  possibly change date from String to dates in both function and  CoreData and use "(date >= %@) AND (date <= %@)" instead of "BEGINSWITH" in predicate
        let itemFetchRequest = NSFetchRequest<Item>(entityName: "Item")
        itemFetchRequest.sortDescriptors = [NSSortDescriptor(key: "category", ascending: true)]
        itemFetchRequest.predicate = NSPredicate(format: "order.user.name == %@", UserDetails.fullName!)
        itemFetchRequest.predicate = NSPredicate(format: "date BEGINSWITH %@", dateToFetch)
        let itemFetchedResultController = NSFetchedResultsController(fetchRequest: itemFetchRequest, managedObjectContext: context, sectionNameKeyPath: "category", cacheName: nil)
        return itemFetchedResultController
    }()

TableView数据源:

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

        // apple doc : trhrows an error : Initializer for conditional binding must have Optional type, not 'NSFetchedResultsController<Item>'
//        if let frc = itemFetchedResultController {
//            return frc.sections!.count
//        }
//        return 0

            return itemFetchedResultController.sections!.count

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        guard let sections = self.itemFetchedResultController.sections else {
            print(" Error :no sections in fetchedResultController" )
            return 0
        }
        let sectionInfo = sections[section]
        return  sectionInfo.numberOfObjects

    }

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "statisticsCell", for: indexPath) as! StatisticsTableViewCell
            cell.idInfoLabel.text = itemFetchedResultController.object(at: indexPath).itemId!
            cell.nameInfoLabel.text = itemFetchedResultController.object(at: indexPath).itemName!

    let item = itemFetchedResultController.object(at: indexPath).itemName!

    let productRequest: NSFetchRequest<Product> = Product.fetchRequest()
    productRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    productRequest.predicate = NSPredicate(format: "name == %@", item)
    productRequest.fetchLimit = 1
    do {
        let fetch = try context.fetch(productRequest)
        cell.productImageView.image = UIImage(data: (fetch[0].productImage! as Data))
        cell.minimumStockInfoLabel.text = fetch[0].minimumStock
        cell.soldQuantityInfoLabel.text = fetch[0].soldQuantity

    } catch  {
        print("Error in fetching product for cell: \(error)")
    }

    return cell
}

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

//        guard let sections = self.itemFetchedResultController.sections else {
//            print(" Error : no sections in itemsFetchedResultController " )
//            return "empty"
//        }
//        let sectionInfo = sections[section]
//        return sectionInfo.name

        guard let sectionInfo = itemFetchedResultController.sections?[section] else {
            return nil
        }
        return sectionInfo.name

    }

        func sectionIndexTitles(for tableView: UITableView) -> [String]? {
//            if let sectionIndexTitles: FetchedResultController.sectionIndexTitles = self.itemFetchedResultController.sectionIndexTitles {
//                print(" Error : no sections in itemsFetchedResultController " )
//                return [""]
//            }
            return itemFetchedResultController.sectionIndexTitles
        }

    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        // apple doc : trhrows an error : Initializer for conditional binding must have Optional type, not 'Int'
//        guard let result = itemFetchedResultController.section(forSectionIndexTitle: title, at: index) else {
//            fatalError("Unable to locate section for \(title) at index: \(index)")
//        }
//        return result
       let result = itemFetchedResultController.section(forSectionIndexTitle: title, at: index)
        return result

    }

1 个答案:

答案 0 :(得分:1)

将您的UITableView样式设置为分组,您的所有部分将与单元格一起滚动

enter image description here