스토리보드를 사용하지 않고 어떻게 새로운 Swift 프로젝트를 만들 수 있습니까?
XCode 6에서 새 프로젝트를 만들면 스토리보드를 비활성화할 수 없습니다.핵심 데이터의 사용 여부는 Swift 또는 Objective-C만 선택할 수 있습니다.
스토리보드를 삭제하고 프로젝트에서 메인 스토리보드를 제거하고 did에서 창을 수동으로 설정했습니다.
AppDelegate에서 다음과 같은 정보를 얻을 수 있습니다.
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow
var testNavigationController: UINavigationController
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
testNavigationController = UINavigationController()
var testViewController: UIViewController = UIViewController()
self.testNavigationController.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window.rootViewController = testNavigationController
self.window.backgroundColor = UIColor.whiteColor()
self.window.makeKeyAndVisible()
return true
}
}
그러나 XCode는 다음과 같은 오류를 표시합니다.
'AppDelegate' 클래스에 이니셜라이저가 없습니다.
이 일에 성공한 사람?
데 은 스토리않데는필것모든한요사입니다.rootViewController:
1· 경변AppDelegate.swift대상:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
window.backgroundColor = UIColor.white
window.rootViewController = ViewController()
window.makeKeyAndVisible()
}
return true
}
}
2· 생성 ViewController의하위의 UIViewController:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
}
3· Xcode 템플릿에서 프로젝트를 생성한 경우:
- 키값키-쌍제거의 합니다.
"Main storyboard file base name"Info.plist. - 파일
Main.storyboard.
에서 볼 수 저는 으로 포장을 푸는 보다, 번째코스볼서수있듯이에저, 암로선대에다신니좋합, 는저오그려아을것히첫는푸택장항는묵적으포을의를 .if let선택 사항의 래핑 해제를 위한 구문window소유물.여기서 나는 그것을 사용합니다.if let a = a { }으로 그서선사항택래사▁the항▁so▁that▁optional선택.a 비적 됩니다 참가조 안에서 할 수 .if - - 같은이문장의름▁–장문▁with -a.
마내침.self.를니참조때않습다필지를 참조할 때는 하지 않습니다.window고유 클래스 내의 속성입니다.
다음을 표시해야 합니다.window그리고.testNavigationController옵션 변수:
var window : UIWindow?
var testNavigationController : UINavigationController?
Swift 클래스를 사용하려면 인스턴스화 중에 옵션이 아닌 속성을 초기화해야 합니다.
클래스 및 구조체는 해당 클래스 또는 구조체의 인스턴스가 생성될 때까지 저장된 모든 속성을 적절한 초기 값으로 설정해야 합니다.저장된 속성은 불확실한 상태로 둘 수 없습니다.
선택적 유형의 속성은 0 값으로 자동으로 초기화되며, 이는 초기화 중에 속성이 의도적으로 "아직 값이 없음"을 의미합니다.
선택적 변수를 사용할 때는 다음과 같이 변수의 랩을 해제해야 합니다.!를 들어 다음과 같습니다.
self.window!.backgroundColor = UIColor.whiteColor();
xib와 함께 viewController를 초기화하고 탐색 컨트롤러를 사용해야 하는 경우.여기 코드 조각이 있습니다.
var window: UIWindow?
var navController:UINavigationController?
var viewController:ViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
viewController = ViewController(nibName: "ViewController", bundle: nil);
navController = UINavigationController(rootViewController: viewController!);
window?.rootViewController = navController;
window?.makeKeyAndVisible()
return true
}
다음 코드를 사용해 보십시오.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
// Create a nav/vc pair using the custom ViewController class
let nav = UINavigationController()
let vc = NextViewController ( nibName:"NextViewController", bundle: nil)
// Push the vc onto the nav
nav.pushViewController(vc, animated: false)
// Set the window’s root view controller
self.window!.rootViewController = nav
// Present the window
self.window!.makeKeyAndVisible()
return true
}
저는 xcode 설정과 관련이 없다는 답을 찾았습니다. 스토리보드를 제거하고 프로젝트에서 참조하는 것이 올바른 것입니다.빠른 구문과 관련이 있었습니다.
코드는 다음과 같습니다.
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.testNavigationController = UINavigationController()
var testViewController: UIViewController? = UIViewController()
testViewController!.view.backgroundColor = UIColor.redColor()
self.testNavigationController!.pushViewController(testViewController, animated: false)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = testNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
다음과 같이 수행할 수 있습니다.
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var IndexNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var IndexViewContoller : IndexViewController? = IndexViewController()
self.IndexNavigationController = UINavigationController(rootViewController:IndexViewContoller)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = self.IndexNavigationController
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
Swift 3.0용으로 업데이트됨:
window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
업데이트: Swift 5 및 iOS 13:
- 단일 보기 응용프로그램을 만듭니다.
- 메인.스토리보드를 삭제합니다(우클릭 후 삭제).
- 의 기본 장면 구성에서 스토리보드 이름 삭제
Info.plist파일: - 열다.
SceneDelegate.swift그리고 변화func scene출처:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
로.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).x
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = ViewController()
self.window = window
window.makeKeyAndVisible()
}
}
컨트롤러와 xib를 사용하는 것이 좋습니다.
MyViewController.swift그리고.MyViewController.xib
(File->New->File->Cocoa Touch Class를 통해 생성하고 "또한 XIB file 생성" true, UIViewController의 하위 클래스를 설정할 수 있습니다.)
class MyViewController: UIViewController {
.....
}
및 인AppDelegate.swift func application다음 코드를 작성합니다.
....
var controller: MyViewController = MyViewController(nibName:"MyViewController",bundle:nil)
self.window!.rootViewController = controller
return true
일이 되어야 합니다!
다음은 UI 내비게이션 컨트롤러에 대한 완전한 신속 테스트 예제입니다.
import UIKit
@UIApplicationMain
class KSZAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Working WITHOUT Storyboard
// see http://randexdev.com/2014/07/uicollectionview/
// see http://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let win = window {
win.opaque = true
//you could create the navigation controller in the applicationDidFinishLaunching: method of your application delegate.
var testViewController: UIViewController = UIViewController()
testNavigationController = UINavigationController(rootViewController: testViewController)
win.rootViewController = testNavigationController
win.backgroundColor = UIColor.whiteColor()
win.makeKeyAndVisible()
// see corresponding Obj-C in https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html#//apple_ref/doc/uid/TP40011313-CH2-SW1
// - (void)applicationDidFinishLaunching:(UIApplication *)application {
// UIViewController *myViewController = [[MyViewController alloc] init];
// navigationController = [[UINavigationController alloc]
// initWithRootViewController:myViewController];
// window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// window.rootViewController = navigationController;
// [window makeKeyAndVisible];
//}
}
return true
}
}
그냥 빈 애플리케이션을 만드는 게 어때요?스토리보드는 내게 만들어지지 않았습니다...
다음과 같이 Xcode 6(iOS 8)에서 스토리보드 없이 내비게이션 기반 애플리케이션을 만들 수 있습니다.
프로젝트 언어를 Swift로 선택하여 빈 응용 프로그램을 만듭니다.
인터페이스 xib를 사용하여 새 코코아 터치 클래스 파일을 추가합니다(예:테스트 보기 컨트롤러)
swift에서는 xib, 즉 *.swift 파일과 상호 작용하는 파일이 하나뿐이며 .h 및 .m 파일은 없습니다.
우리는 iOS 7에서와 같이 xib의 컨트롤을 swift 파일로 연결할 수 있습니다.
다음은 컨트롤 및 Swift 작업을 위한 몇 가지 스니펫입니다.
//
// TestViewController.swift
//
import UIKit
class TestViewController: UIViewController {
@IBOutlet var testBtn : UIButton
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
@IBAction func testActionOnBtn(sender : UIButton) {
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert's cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
AppDelegate.swift 파일의 변경 사항
//
// AppDelegate.swift
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController = UINavigationController(rootViewController: testController)
self.window!.rootViewController = self.navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/ 에서 코드 샘플 및 기타 정보를 찾을 수 있습니다.
iOS 13 이상에서는 스토리보드 없이 새 프로젝트를 만들 때 다음 단계를 사용합니다.
- Xcode 11 이상을 사용하여 프로젝트 생성
- 스토리보드 니브 및 클래스 삭제
- xib를 사용하여 새 파일 추가
- 루트 뷰를 UINavigationController SceneDelegate로 설정해야 합니다.
- 아래 코드 추가:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// guard let _ = (scene as? UIWindowScene) else { return }
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
let mainController = HomeViewController() as HomeViewController
let navigationController = UINavigationController(rootViewController: mainController)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
}
}
언급URL : https://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards
'codememo' 카테고리의 다른 글
| Android가 프로세스를 죽이는 시뮬레이션 방법 (0) | 2023.08.06 |
|---|---|
| 도커 이미지를 하나의 컨테이너에 결합하는 방법이 있습니까? (0) | 2023.08.06 |
| Google 지도 Android API v2 - Interactive InfoWindow(원래 Android Google 지도와 동일) (0) | 2023.08.06 |
| AJAX Post를 통해 파일 판독기 이진 데이터로 파일 입력 게시 (0) | 2023.08.06 |
| 여러 스레드에서 Bhem GC를 독립적으로 실행 (0) | 2023.08.01 |