我想在用户按下UI按钮时,仅使用Swift中的代码,从ViewController转换到secondViewController.

//Function to transition
func transition(Sender: UIButton!)
{   
    //Current Code, default colour is black
    let secondViewController:UIViewController = UIViewController()
    self.presentViewController(secondViewController, animated: true, completion: nil)

 }

推荐答案

问题是,您的代码正在创建一个空白的UIViewController,而不是SecondViewController.您需要创建子类的实例,而不是UIViewController,

func transition(Sender: UIButton!) {   
    let secondViewController:SecondViewController = SecondViewController()

    self.presentViewController(secondViewController, animated: true, completion: nil)

 }

如果您已经重写了init(nibName nibName:String!、bundle nibBundle:NSBundle!)在第二个ViewController类中,需要将代码更改为,

let sec: SecondViewController = SecondViewController(nibName: nil, bundle: nil)

Swift相关问答推荐

ScrollView中的视频渲染不流畅

SON数组到属性

使用简单变量和函数的奇怪行为

JSON如何解码空对象

为什么在Swift属性Wrapper中需要类型注释?

如何在向照片添加文本时定义文本对齐、文本背景的Alpha和在文本之前添加图像

如何在visionOS上删除PhotosPicker背景 colored颜色 ?

try 在小部件内部读取核心数据的SwiftUI总是返回空吗?

无论玩家移动到视图内的哪个位置,如何使用 SpriteKit 让敌人向玩家emits 子弹?

我如何在 swift 中的 viewdidload 之前进行委托?

为什么Swift可以在没有足够信息的情况下推断类型?

为什么 UITapGestureRecognizer 对于 Swift 集合视图中的单元格图像无法正常工作?

在领域 SwiftUI 异常中使用 Apple 登录:无法识别的 Select 器发送到实例

@Binding 在@StateObject 和 View 上被发布了两次?

是否有一个带有空初始值设定项的 Swift 类/ struct 的标准协议

如何确定扩展中的具体类型?

如何在 Swift 中的两个 UIView 中心之间添加线?

FirebaseStorage:如何删除目录

不支持用作符合协议 AnyObject 的具体类型

FCM 后台通知在 iOS 中不起作用