将数据传递给 iOS UIViewController

Issue passing data to iOS UIViewController

我试图将枚举传递给另一个故事板中的 UIViewController,但错误是 UIViewController 没有成员 ViewType。当我在强制 ! 后检查变量类型时,它仍然是 UIViewController 而不是 QuotesTestmoniesViewController

为什么变量的类型没有被更改为新的视图控制器类型?我在这里做错了什么?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
    var viewController = UIViewController()
    
    switch indexPath.item {
    //Saints
    case 0:
        viewController = self.amiStoryboard.instantiateViewController(withIdentifier: "militarysaintscontroller") as! SaintsViewController
        self.navigationController?.pushViewController(viewController, animated: true)
    //Prayers
    case 1:
        break;
    //Testmonies
    case 2:
        break;
    //Quotes
    case 3:
        viewController = self.amiStoryboard.instantiateViewController(withIdentifier: "militaryquotestestmoniescontroller") as! QuotesTestmoniesViewController
        viewController.viewType = ViewType.Quotes //ERROR
        self.navigationController?.pushViewController(viewController, animated: true)
    default:
        return
    }
}

T 类型的变量可以保存 T 类型的值。如果您使用将 T 转换为 U 的表达式对其进行赋值,则无关紧要。仍然是 T 类型的变量。

看起来您正在尝试使用单行来推送不同的视图控制器。

但是在代码中,您也为所有情况编写了推送线。

它不会通过转换值和赋值来工作。您必须在传递数据时投射控制器。像这样

(viewController as? QuotesTestmoniesViewController).viewType = ViewType.Quotes

你可以像这样创建一个推送视图控制器的通用函数

func pushNextViewController<T: UIViewController>(viewController: T) {
   self.navigationController?.pushViewController(viewController, animated: true)
}

用法:

let viewController = self.amiStoryboard.instantiateViewController(withIdentifier: "militaryquotestestmoniescontroller") as! QuotesTestmoniesViewController
      viewController.viewType = ViewType.Quotes
pushNextViewController(viewController: viewController)

//----

let viewController2 = self.amiStoryboard.instantiateViewController(withIdentifier: "militarysaintscontroller") as! SaintsViewController
pushNextViewController(viewController: viewController2)