代码出处cocoachina
必须包含文件是HPThemeManager.h和HPThemeManager.m
再HPThemeManager.h里申明一个主题的字典,主题索引和当前主题
NSDictionary *themeDictionary;
NSInteger currentThemeIndex;
NSString *currentTheme;
在HPThemeManager.m里初始化主题
-(id)init
{
self = [super init];
if(self)
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"themes" ofType:@"plist"];
themeDictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
self.currentThemeIndex = 0;
self.currentTheme = @"maroon"; //default theme
}
return self;
}
在resourece文件夹里添加了名为themes的plist文件,里面存放主题名。
设置初始主题为maroon
每次加载主题的素材时都从目录加载
-(void)updateTheme:(NSNotification*)notif
{
NSString *themename = [HPThemeManager sharedThemeManager].currentTheme;
NSString *themePathTmp = [[[HPThemeManager sharedThemeManager] themeDictionary] objectForKey:themename];
NSString *themePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:themePathTmp];
if(themePath){
settingTable.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[themePath stringByAppendingPathComponent:@"background.png"]]];
[backButton setImage:[UIImage imageWithContentsOfFile:[themePath stringByAppendingPathComponent:@"back.png"]] forState:UIControlStateNormal];
navback.image = [UIImage imageWithContentsOfFile:[themePath stringByAppendingPathComponent:@"nav.png"]];
}
NSLog(@"%@",themePath);
}
在选择主题的tableview中加如下代码
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *selectName = [themes objectAtIndex:indexPath.row];
[[HPThemeManager sharedThemeManager] setCurrentTheme:selectName]; //must set before post
[[HPThemeManager sharedThemeManager] setCurrentThemeIndex:indexPath.row];
[[NSNotificationCenter defaultCenter] postNotificationName:kThemeDidChangeNotification
object:nil
userInfo:[NSDictionary dictionaryWithObject:selectName forKey:@"selectedTheme"]];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
在放入主题素材的文件夹时一定要将整个文件夹加入