在用户选择联系人(method didSelect contact)之后,我只想重新加载单个单元格。如果单元格中的项目数变大,则过程会变慢。我也尝试在DispatchQueue.main.async { code }中实现,并且仍然需要一些时间来加载。

cellForItemAt和noOfItemInSection(AddCell)-总单元格4

var indexPaths = [IndexPath]()

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   indexPaths.append(indexPath)

   if indexPath.item == 1 {
        let addCell = collectionView.dequeueReusableCell(withReuseIdentifier: CellId, for: indexPath) as! AddCell
        addCell.btnAdd.addTarget(self, action: #selector(handleOpenContact), for: .touchUpInside)
        addCell.invitees = invitees
        return addCell
    }
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }


cellForItemAt和noOfItemInSection(SubAddCell)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: subAddId, for: indexPath) as! SubAddCell
        cell.delegate = self
        cell.invitee = invitees[indexPath.item]
        return cell
    }

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


didSelect(ContactPicker)

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        let invitee = Invitee()
        invitee.name = contact.givenName

        if contact.isKeyAvailable(CNContactPhoneNumbersKey) {
            for phoneNumber: CNLabeledValue in contact.phoneNumbers {
                let a = phoneNumber.value
                print("\(a.stringValue)")
                invitee.phoneNo = a.stringValue
            }
        }
        self.invitees.append(invitee)

        for index in self.indexPaths {
            if index == [0, 0] {
                print(index)
                self.collectionView?.reloadItems(at: [index])
            }
        }
    }


我在indexPaths方法中获得了cellForItemAt的值。如果被邀请者包含5个项目,print(index)将打印19个值。我不知道为什么。下面是图像。

swift - Swift-UICollectionView reloadItems花费太长时间-LMLPHP

用户界面的设计

swift - Swift-UICollectionView reloadItems花费太长时间-LMLPHP

如何优化reloadItems?

任何帮助都非常感谢。非常感谢。

最佳答案

我认为您在indexPaths.append(indexPath)中有这个cellForItemAt,以便为什么在重新加载数据后indexPaths可以增加。您可以使用NSSet而不是NSArray来确保您的对象是唯一的。

并使用cell.invitee = invitees[indexPath.item],您是否为invitee实现didSet?
如果您这样做了,我认为需要先在后台队列中准备数据。例如。

DispatchQueue(label: "queue").async {
  let image = <# process image here #>
  let name = <# process name here #>
  DispatchQueue.main.async {
    self.imageView.image = image
    self.label.text = name
  }
}


希望我的技巧能对您有所帮助!

10-08 16:59