1. 程式人生 > >swift 4.2 - 根據字串 push指定控制器

swift 4.2 - 根據字串 push指定控制器

倆個方法

1.

 /// 指定字串VC跳轉,設定title
    func pushVcByVcNameAndTitle(vcName:String, vcTitleName:String = "", isHideBottomBar:Bool = false){
        if let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"]as? String{
            let clsName = namespace + "." + vcName
            if let cls = NSClassFromString(clsName) as? UIViewController.Type{
                let vc = cls.init()
                vc.title = vcTitleName
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }

  

 

2.

    /// 根據字串獲得對應控制器,使用的時候as, 傳遞引數
    func pushVcByVcNameAndTitle(vcName:String) -> UIViewController?{
        if let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"]as? String{
            let clsName = namespace + "." + vcName
            if let cls = NSClassFromString(clsName) as? UIViewController.Type{
                let vc = cls.init()
                return vc
            }
        }
        return nil
    }

  

3.使用 : 我這裡是tableview使用的

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //這裡 VC需要傳遞引數進去的
        var pushVc : UIViewController?

//具體VC 設定 vc的屬性 if let vc1 = pushVcByVcNameAndTitle(vcName: vcNameArr[indexPath.section][indexPath.row]) as? JYWorksShowController{ vc1.title = titleArr[indexPath.section][indexPath.row] //vc1.arr = self.dataArr //vc1.title = vcTitleArr[index.row] pushVc = vc1 } //這是主頁面看需求隱藏tabbar self.hidesBottomBarWhenPushed = true if let vc = pushVc{ self.navigationController?.pushViewController(vc, animated: true) }else{ //這裡不需要指定控制器。設定VC的屬性的。 pushVcByVcNameAndTitle(vcName: vcNameArr[indexPath.section][indexPath.row], vcTitleName: titleArr[indexPath.section][indexPath.row], isHideBottomBar: true) } //跳轉開啟,不然回到首頁 沒有tabbar self.hidesBottomBarWhenPushed = false }