如何以编程方式在swift 3中添加第二个视图
我试图从第一个视图上的button切换到第二个视图,并以编程方式执行此操作(不使用在故事板上使用segue在视图之间切换的传统方式)
我目前的应用程序委托:
import UIKit @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate { public var window: UIWindow? public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.rootViewController = UINavigationController(rootViewController: ViewController()) return true }
第一个视图控制器中的buttonfunction,当按下时应该切换到新的视图:
func signupAction (sender: UIButton!){ }
我已经创build了新的viewcontroller文件:
class Signup: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.cyan } }
基本上,我试图实现第一个视图控制器中的button转换到这个注册视图控制器。
如果您在UINavigationController
,则可以按照以下方式将Signup
视图控制器推送到导航堆栈:
let storyboard = UIStoryboard(name: "Main", bundle: nil) let signUpViewController = storyboard.instantiateViewController(withIdentifier: "signUpViewController") as! Signup navigationController?.pushViewController(signUpViewController, animated: true)
如果您不在UINavigationController
并想要显示它,可以这样做:
let storyboard = UIStoryboard(name: "Main", bundle: nil) let signUpViewController = storyboard.instantiateViewController(withIdentifier: "signUpViewController") as! Signup self.present(signUpViewController, animated: true, completion: nil)
注意:不要忘记在故事板中设置视图控制器的标识符。