您的位置:首页 > 移动开发 > IOS开发

给你的iOS应用更换主题

2016-01-08 20:28 489 查看
应用主题的更换往往会给我们的应用添彩,今天总结一下iOS主题切换的方法

1.首先把各个主题图片导入到工程目录中



选择Create folder references

2.Thememanager.h中声明单例方法和传入图片或者颜色的名字对应找到图片和颜色

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Thememanager : NSObject

@property(nonatomic, copy) NSString *currentTheme;

@property(nonatomic, retain, readonly) NSDictionary *themeDic;

@property(nonatomic, retain, readonly) NSDictionary *themeColorDic;

+(instancetype)defaultManager;

//凭借图片路径并且放回图片对象
-(UIImage *)imageFromName:(NSString *)imgName;

//传入颜色对应的pilst文件中名字 获取uicolor颜色
-(UIColor *)colorFromName:(NSString *)colorName;

@end


3.创建主题管理类来管理主题的切换,Thememanager.m中要创建单例方法

//获取单例对象
+(instancetype)defaultManager
{
static Thememanager *themeManager = nil;

static dispatch_once_t predicate;

dispatch_once(&predicate, ^{

themeManager = [[Thememanager alloc] init];

});

return themeManager;
}


4.复写init初始化方法获取plist文件中数据对应切换主题

//复写init初始化方法
-(instancetype)init
{
self = [super init];

if (self) {

//1.获取文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"theme" ofType:@"plist"];

//2.解析plist数据
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];

//设置主题数据
_themeDic = dic;

//设置初始的主题
_currentTheme = @"猫爷";

}

return self;
}


5.实现根据名字找到图片的方法(地址拼接)

//凭借图片路径并且放回图片对象
-(UIImage *)imageFromName:(NSString *)imgName
{
//获取当前工作目录
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];

NSString *imgpath = [self.themeDic objectForKey:self.currentTheme];

NSString *path = [NSString stringWithFormat:@"%@/%@/%@",bundlePath,imgpath,imgName];
//    NSLog(@"path is:%@",path);

return [[UIImage alloc] initWithContentsOfFile:path];

}


6.复写currenttheme的set方法,当主题切换时发送通知

//复写currenttheme的set方法
-(void)setCurrentTheme:(NSString *)currentTheme
{
_currentTheme = currentTheme;

//主题切换时获取新的 颜色的config。plist文件数据

//获取到当前主题对应的路径
NSString *themePath = [self.themeDic objectForKey:_currentTheme];

//凭借configpist文件路径
NSString *configPath = [NSString stringWithFormat:@"%@/%@/config.plist",[[NSBundle mainBundle] bundlePath],themePath];

//根据路径解析plist文件数据
_themeColorDic = [NSDictionary dictionaryWithContentsOfFile:configPath];

//当主题切换时发起通知
[[NSNotificationCenter defaultCenter] postNotificationName:kThemeChanageNotification object:nil];
}


7.在切换主题的类中通过单例拿到图片切换主题

-(instancetype)initWithImage:(UIImage *)image
{
self = [super initWithImage:image];
if (self) {
[[NSNotificationCenter defaultCenter] addObserverForName:kThemeChanageNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {

//重新设置图片
//            self.image = [[Thememanager defaultManager] imageFromName:self.imgName];

self.image = kThemeImageFromName(self.imgName);
}];

}
return self;
}


转自我的博客http://rockeen.cn/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: