swift InstantiateViewController(标识符:创建者:)“仅在iOS 13.0或更高版本中可用

xbp102n0  于 2023-02-03  发布在  Swift
关注(0)|答案(4)|浏览(168)

我收到此错误-InstantiateViewController(标识符:creator:)"仅在iOS 13.0或更高版本中可用
为了解决这个问题,我不得不使用这样一个条件:

if #available(iOS 13.0, *) {

}

但是如何在没有这个条件的情况下解决这个问题。
我的代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let vc = storyboard?.instantiateViewController(identifier: "CartViewController") as? CartViewController
        vc?.bookNameToSend = bookName[indexPath.row]
        vc?.bookImageToSend = bookImage[indexPath.row]
        self.navigationController?.pushViewController(vc!, animated: true)
    }
}
ibps3vxo

ibps3vxo1#

在iOS 13中,苹果引入了这种新方法instantiateViewController(identifier:creator:),这会造成混乱,但旧方法仍然存在。
因此请改用instantiatViewController(withIdentifier:)

let vc = storyboard?.instantiateViewController(withIdentifier: "CartViewController") as? CartViewController
a0x5cqrl

a0x5cqrl2#

在iOS 13中,参数名称为identifier,在iOS 13版本以下,参数名称为withIdentifier

if #available(iOS 13.0, *) {
        let vc = storyboard.instantiateViewController(identifier: "doctorProfileVC") as DrProfileViewController
        self.navigationController?.pushViewController(vc, animated: true)

    } else {
        let vc = storyboard.instantiateViewController(withIdentifier: "storyboard.instantiateViewController") as! DrProfileViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
rsaldnfx

rsaldnfx3#

你可以不用检查iOS版本就可以完成你的工作。为了更容易,你只需要添加两个常用的方法作为扩展。--〉

extension UIStoryboard {
    // MARK: - Convenience Initializers
    convenience init(storyboard: String, bundle: Bundle? = nil) {
        self.init(name: storyboard, bundle: bundle)
    }
    
    // MARK: - View Controller Instantiation from Generics
    func instantiateViewController<T>(withIdentifier identifier: T.Type) -> T where T: StoryboardIdentifiable {
        let className = String(describing: identifier)
        weak var weakSelf = self
        guard let vc =  weakSelf?.instantiateViewController(withIdentifier: className) as? T else {
            fatalError("Cannot find controller with identifier \(className)")
        }
        return vc
    }
}

现在在你的viewController中,你可以像这样使用它们--〉

private func goToYourTargetedViewController(){
        let storyboard = UIStoryboard(storyboard: "YourTargetedStoryboardName")
        let vc = storyboard.instantiateViewController(withIdentifier: YourTargetedViewControllerName.self)
        self.navigationController?.pushViewController(vc, animated: true)
    }

每当你想导航到你的目标viewController时调用这个私有方法。

n1bvdmb6

n1bvdmb64#

我认为解决这个问题的唯一方法是将项目的最低目标版本更改为iOS 13或避免使用该特定方法,否则您将不得不使用if条件。

相关问题