ios適配iPhone和iPad

最近項目需要兼容iPad,由于項目使用xib和Storyboard,故記錄對iPhone和iPad的適配!

iPhone和ipad適配分為兩種種:

1.為iPad和iPhone分別開發(fā)不同的項目(適合兩個項目區(qū)別比較大,要分別發(fā)布)

2.一個項目同時兼容iPhone和iPad;

本文只對第二種情況(一個安裝包同時兼容iPhone和ipad)

要在一個工程中兼容ipad和iPhone步驟:

1.設(shè)置targets->Deployment Info ->Devices 選擇Universal


Storyboard:

2.選中storyboard文件,假設(shè)名字為Main.storyboard;

3.File--->duplicate,將文件命名為Main_ipad.storyboard:(注意一點要設(shè)置為_ipad,需要和下面的代碼匹配)

4.右鍵Main_ipad.storyboard,open as ---> source code,找到targetRuntime,將其修改為targetRuntime="iOS.CocoaTouch.iPad"

5、調(diào)用storyboardWithName方法改為storyboardAdapter;

針對5需要為UIStoryboard建類別UIStoryboard+Adapter

UIStoryboard+Adapter.h

#import

@interfaceUIStoryboard (Adapter)

+ (UIStoryboard*_Nullable)storyboardAdapter:(nonnullNSString*)name bundle:(nullableNSBundle*)storyboardBundleOrNil;

@end

UIStoryboard+Adapter.m

#import"UIStoryboard+Adapter.h"

@implementationUIStoryboard (Adapter)

+ (UIStoryboard*)storyboardAdapter:(NSString*)name bundle:(nullableNSBundle*)storyboardBundleOrNil

{

UIStoryboard*storyBoard;

if((UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)) {

NSString*ipad = [namestringByAppendingString:@"_ipad"];

storyBoard = [UIStoryboardstoryboardWithName:ipadbundle:storyboardBundleOrNil];

}

else

{

storyBoard = [UIStoryboardstoryboardWithName:namebundle:storyboardBundleOrNil];

}

returnstoryBoard;

}

@end

使用方法:

UIStoryboard*storyBoard = [UIStoryboard storyboardAdapter:@"Main"bundle:nil];

Xib:

前四步一樣,第五步:需要新建UIViewController類別?UIViewController+Adapter

UIViewController+Adapter.h

@interfaceUIViewController (Adapter)

- (instancetype_Nullable)initWithAdapterNibName:(nullableNSString*)nibNameOrNil bundle:(nullableNSBundle*)nibBundleOrNil;

@end

UIViewController+Adapter.m

@implementationUIViewController (Adapter)

- (instancetype)initWithAdapterNibName:(nullableNSString*)nibNameOrNil bundle:(nullableNSBundle*)nibBundleOrNil

{

UIViewController*tmpVC;

if((UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)) {

NSString*ipad = [nibNameOrNilstringByAppendingString:@"_ipad"];

tmpVC = [selfinitWithNibName:ipadbundle:nibBundleOrNil];

}

else

{

tmpVC = [selfinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];;

}

returntmpVC;

}

@end

最后針對ipad和iPhone圖片的兼容:

使用Assets.xcassets選擇圖片后->Devices中選擇iPhone和iPad


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容