雖然storyboard是個對初學者比較方便使用的東西,但是當你有很多元件要用,修改來講的話就就會比較麻煩,所以我們可以使用Xib來做UI設計,它的介面是跟storyboard一樣的,唯一不同的是,它可以是一個個檔案,這樣我們要修改元件,就可以針對一個檔案去做修改~
第一步:找到Main Interface後,裡面有個Main Interface,直接把它清除
清除後:
第二步:點開info.plist
進去之後我們會看到這一長串的東西,從Application Scene Mainifest一直展開,直到看到Storyboard Name,把Storyboard Name整行刪掉~
刪除後長這樣:
接者把ViewContriller.swift跟Main.storyboard這兩個檔案刪掉
刪除後:
接者我們新增一個資料夾取名叫做MainVC,之後在資料夾底下新增檔案,檔案類型為Cocoa Touch Class
然後檔案名稱叫做MainVC,當然你可以取你喜歡的名稱,Subclass記得選UIViewController,最最重要的,一定要勾Also create XIB file~
好了之後我們回到我們的Main Interface
打開下拉式選單,選MainVC.xib(剛剛建立的)
如果你的安裝版本是IOS13以下(不含13),要在AppDelegate底下加入這段程式碼:
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let rootVC = HelloViewController(nibName: String(describing: HelloViewController.self), bundle: nil)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = rootVC
window?.makeKeyAndVisible()
return true
}
同時你也要在Scene Delgate加入這段程式碼:
@available(iOS 13.0, *)//寫在class外面
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let rootVC = MainVC(nibName: "MainVC", bundle: nil)
let navigationController = UINavigationController(rootViewController: rootVC)
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
}
如果是13以上(包含13),你只要在SceneDelegate加入這段就好
:
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let rootVC = MainVC(nibName: "MainVC", bundle: nil)
let navigationController = UINavigationController(rootViewController: rootVC)
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
}
結果: