标签:
建立UITabController时,将几个uiviewcontroller初始化后放入数组,然后通过UITabController进行串联。但是在初始化uiviewcongroller和配置控件的时候会出现很多重复的代码,对后期的维护会带来很多不便。因此通过建立一个plist文件,通过model来优化代码。
1.建立一个plist文件,在文件中添加相关控件的名称。
2.在model中将plist文件中的控件名取出来并赋值。
3.在UITabController中初始化model,引入各uiviewcontroller。
第一步:
第二步:
1 #import "BaseInfo.h" 2 #import <UIKit/UIKit.h> 3 @interface PageInfo : BaseInfo 4 @property (nonatomic,strong)NSString *image; 5 @property (nonatomic,strong)NSString *SelectedImage; 6 7 +(NSArray *)pageControllers; 8 9 @end
1 #import "PageInfo.h" 2 3 @implementation PageInfo 4 //通过类方法,将传来的NSDictionary中相应的元素解析出来,返回解析出来的model 5 +(PageInfo *)infoFromDict:(NSDictionary *)dict 6 { 7 PageInfo *info = [[PageInfo alloc]init]; 8 info.ID = [dict valueForKey:@"Class Name"]; 9 info.name = [dict valueForKey:@"Title"]; 10 info.image = [dict valueForKey:@"Image"]; 11 info.SelectedImage = [dict valueForKey:@"SelectedImage"]; 12 return info; 13 } 14 +(NSArray *)pages 15 { 16 //找到建立的plist文件路径 17 NSString *confile = [[NSBundle mainBundle]pathForResource:@"HomeList" ofType:@"plist"]; 18 //将plist文件中定义的NSArray拿到 19 NSArray *pageConfign = [NSArray arrayWithContentsOfFile:confile]; 20 NSMutableArray *pages = [[NSMutableArray alloc]init]; 21 22 if (pageConfign.count <= 0) { 23 NSLog(@"NO LIST"); 24 } 25 //遍历plist文件中的Array,并将数组中的字典解析并配置为model,然后将配置好的model添加到可变数组中,返回可变数组 26 for (NSDictionary *dict in pageConfign) { 27 [pages addObject:[PageInfo infoFromDict:dict]]; 28 } 29 return pages; 30 } 31 +(NSArray *)pageControllers 32 { 33 //取到pages方法中返回的数组 34 NSMutableArray *controllers = [NSMutableArray array]; 35 NSArray *page = [PageInfo pages]; 36 UIViewController *pageController = nil; 37 UINavigationController *napage = nil; 38 //将取到的数组将model中定义的各类,赋值给相应的控件,返回 39 for (PageInfo *pageInfo in page) { 40 pageController = [[NSClassFromString(pageInfo.ID) alloc]init]; 41 napage = [[UINavigationController alloc]initWithRootViewController:pageController]; 42 pageController.title = pageInfo.name; 43 pageController.tabBarItem.image = [UIImage imageNamed:pageInfo.image]; 44 pageController.tabBarItem.selectedImage = [UIImage imageNamed:pageInfo.SelectedImage]; 45 [controllers addObject:napage]; 46 } 47 return controllers; 48 } 49 @end
第三步
1 @implementation HomePage 2 3 -(instancetype)init{ 4 self = [super init]; 5 if (self) { 6 [self addTabController]; 7 } 8 return self; 9 } 10 -(void)viewDidLoad{ 11 [super viewDidLoad]; 12 13 } 14 -(void)addTabController 15 { 16 17 self.tabBar.tintColor = [UIColor redColor]; 18 self.viewControllers = [PageInfo pageControllers]; 19 } 20 - (void)didReceiveMemoryWarning { 21 [super didReceiveMemoryWarning]; 22 } 23 24 @end
标签:
原文地址:http://www.cnblogs.com/moxuexiaotong/p/4865282.html