在自學的初期,我們通常使用storyboard來作爲我們的view,創建我們的工程,但是由於合作開發的需要,
我們也可以不使用storyboard,而是使用XIB的方式創建我們的項目,
下面我們逐步的創建我們的項目,本人折騰了一下午才弄好,期間走了很多彎路。。。
1 . 創建single view application,然後刪除Main.storyboard,創建一個xib文件
2 . 在Info.plist中,刪除Main storyboard file base name所在的項
3 . 我們開始編輯xib文件,在本文,我的xib文件名爲View.xib
a . 首先點擊如下圖所示的File’s owner, 設置identity inspector裏的class爲對應的ViewController類
b. 因爲ViewController類繼承自UIViewController類,所以有成員view,對應顯示界面的根view,我們需要把xib的view與ViewController類中的view對應起來,這樣才能顯示正常,
c. 添加一些控件,我們添加最簡單的label
在xib中拖入空間,然後用ctrl+拖拽的方式,將outlet添加到ViewController的頭文件中
xib的修改就完成了
4 . 因爲以前用storyboard的時候,會有一個入口的箭頭,我們運行程序的時候會在箭頭處開始執行,但是xib方式沒有這個箭頭,怎麼辦呢?在AppDelegate.m中添加代碼調用: 我們在如下函數中添加內容:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//創建ViewController實例
ViewController *viewController = [[ViewController alloc] initWithNibName:@"View" bundle:nil];
CGRect rect = self.window.bounds;
viewController.view.frame = rect;
//設置window根視圖控制器
self.window.rootViewController = viewController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
這裏面綁定了對應的xib文件,並且對佈局進行了設置。
爲了觀察方便,我們可以把xib文件view的背景顏色設置成藍色
我們可以發現,我們的view是鋪滿整個界面的,但是label並沒有在中間,如何通過代碼設置label呢?
5 . 代碼控制label
我們已經在ViewController.h文件中聲明瞭label的outlet,所以我們在對應的實現文件ViewController.m中,添加如下函數:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
CGRect rect = self.view.bounds;
NSLog(@"view rect width %f, height %f\n",rect.size.width, rect.size.height);
CGPoint point = CGPointMake(rect.origin.x + rect.size.width/2,rect.origin.y + rect.size.height/2);
_helloLabel.center = point;
[_helloLabel setTextAlignment: NSTextAlignmentCenter];
}
(我嘗試過在viewDidLoad和viewWillAppear中添加這些內容,但是並不生效,而且讀出來的rect也非常詭異,對於iOSview調用的具體順序,我水平有限,不是很瞭解,還請大家賜教)
這時候運行程序,應該就可以正常顯示了,
使用xib方式創建的工程有些複雜,還需要繼續學習,希望能和大家切磋
需要注意的是,有些帖子裏說,需要把LaunchScreen.xib相關的內容一併刪掉,但是我發現刪掉以後,會造成無論如何都無法全屏顯示的結果,具體原因未知,初入iOS,還有很多未知,希望大家多多指點