在我的应用程序中,我有UITabBarController
,其中放置了UIContainerView
,以便在其中显示一组不同的页面。
默认情况下,屏幕1从一开始就使用情节提要板加载到该容器中。
以下是添加UIViewControllers
到容器视图并在添加新容器时删除的代码:
@objc func switchContainerViewContent() {
switch viewControllerId {
case "1":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "MedicalInsurancePolicyScreen") as? MedicalInsuranceScreenViewController else {
return
}
self.add(childVC, frame: self.containerView.frame)
case "2":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "HouseInsurancePolicyScreen") as? HouseInsuranceScreenViewController else {
return
}
self.add(childVC, frame: self.containerView.frame)
case "3":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "CarInsurancePolicyScreen") as? CarInsuranceScreenViewController else {
return
}
self.add(childVC, frame: self.containerView.frame)
default:
break
}
}
@objc func removePreviousChildViewContent() {
switch viewControllerId {
case "1":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "MedicalInsurancePolicyScreen") as? MedicalInsuranceScreenViewController else {
return
}
childVC.remove()
case "2":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "HouseInsurancePolicyScreen") as? HouseInsuranceScreenViewController else {
return
}
childVC.remove()
case "3":
guard let childVC = self.storyboard?.instantiateViewController(withIdentifier: "CarInsurancePolicyScreen") as? CarInsuranceScreenViewController else {
return
}
childVC.remove()
default:
break
}
}
在此处添加和删除func本身:
func add(_ child: UIViewController, frame: CGRect? = nil) {
addChildViewController(child)
if let frame = frame {
child.view.frame = frame
}
view.addSubview(child.view)
child.didMove(toParentViewController: self)
}
func remove() {
willMove(toParentViewController: nil)
view.removeFromSuperview()
removeFromParentViewController()
}
这是用于处理容器内内容切换的集合视图:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedPolicyIndex = indexPath
guard let cell = collectionView.cellForItem(at: selectedPolicyIndex) as? PoliciesCell else { return }
cell.selectionView.isHidden = false
cell.policyNumber.isHidden = true
cell.policyName.isHidden = true
collectionView.reloadData()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "removePreviousPolicy"), object: nil)
switch indexPath.item {
case 0:
viewControllerId = "1"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "switchPolicies"), object: nil)
case 1:
viewControllerId = "2"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "switchPolicies"), object: nil)
case 2:
viewControllerId = "3"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "switchPolicies"), object: nil)
default:
break
}
}
在TabBar中从一个选项卡切换到另一个选项卡时,出现错误。由于某种原因,我的容器会记住该容器中显示的所有屏幕,并在我再次打开该标签页时依次加载它们。
更具体地说,会发生以下情况:
执行10-15次此操作后,所有这些都会导致内存使用率增加。
我做错了什么?