最近项目需要兼容iPad,由于项目使用xib和Storyboard,故记录对iPhone和iPad的适配!
iPhone和ipad适配分为两种种:
1.为iPad和iPhone分别开发不同的项目(适合两个项目区别比较大,要分别发布)
2.一个项目同时兼容iPhone和iPad;
本文只对第二种情况(一个安装包同时兼容iPhone和ipad)
要在一个工程中兼容ipad和iPhone步骤:
1.设置targets->Deployment Info ->Devices 选择Universal
Storyboard:
2.选中storyboard文件,假设名字为Main.storyboard;
3.File--->duplicate,将文件命名为Main_ipad.storyboard:(注意一点要设置为_ipad,需要和下面的代码匹配)
4.右键Main_ipad.storyboard,open as ---> source code,找到targetRuntime,将其修改为targetRuntime="iOS.CocoaTouch.iPad"
5、调用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