iOS开发之主题皮肤

时间:2023-03-10 03:05:14
iOS开发之主题皮肤
分类: 【iOS】 

最近在开发一款【公交应用】,里面有个模块涉及到主题设置,这篇文章主要谈一下个人的做法。

大概的步骤如下:

(1):整个应用依赖于一个主题管理器,主题管理器根据当前的主题配置,加载不同主题文件夹下的主题

(2):在应用的各个Controller中,涉及到需要更换主题图片或颜色的地方,由原来的硬编码方式改为从主题管理器获取(此处可以看到,虽然.xib配置UI会比编码渲染UI效率来得高,但在灵活性以及协同开发方面还是有些弱了)

(3):在主题设置Controller中,一旦切换主题,则需要像系统的通知中心发送消息(这一步的目的,主要是为了让那些已经存在的并且UI已构建完成的对象修改他们的主题)

最终的效果图见:

https://github.com/yanghua/iBus#version-102preview

首先来看看主题文件夹的目录结构:

iOS开发之主题皮肤

可以看到,通常情况下主题都是预先做好的,当然了,这里因为我没有后端server,如果你的应用是拥有后端server的,那么可以做得更加强大,比如不将主题文件存储在Bundle中,而是存储在应用sandBox的Document中。这样你在应用启动的时候就可以check server 是否有新的主题包,如果有就download下来,释放到Document,这样会方便许多,而不需要在升级之后才能够使用新主题。扯远了,这里可以看到这些文件夹是蓝颜色的,而非黄颜色,可见它不是xcode project的Group,它们都是真实存储的文件夹(它们也是app的bundle的一部分,只是获取的方式有些不同罢了,这样做的目的就是为了方便组织各个主题的文件、目录结构)。

看看获取主题文件夹路径的方式:

  1. #define Bundle_Of_ThemeResource                                @"ThemeResource"
  2. //the path in the bundle
  3. #define Bundle_Path_Of_ThemeResource                                        \
  4. [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:Bundle_Of_ThemeResource]

ThemeManager:

  1. @interface ThemeManager : NSObject
  2. @property (nonatomic,copy) NSString                 *themeName;
  3. @property (nonatomic,copy) NSString                 *themePath;
  4. @property (nonatomic,retain) UIColor                *themeColor;
  5. + (ThemeManager*)sharedInstance;
  6. - (NSString *)changeTheme:(NSString*)themeName;
  7. - (UIImage*)themedImageWithName:(NSString*)imgName;
  8. @end

可以看到,ThemeManager对外开放了三个属性以及两个实例方法,并且ThemeManager被构建为是单例的(Single)

在实例初始化的时候,同时实例化主题的相关配置:
  1. - (id)init{
  2. if (self=[super init]) {
  3. [self initCurrentTheme];
  4. }
  5. return self;
  6. }

initCurrentTheme定义:

  1. - (void)initCurrentTheme{
  2. self.themeName=[ConfigItemDao get:@"主题设置"];
  3. NSString *themeColorStr=[ConfigItemDao get:self.themeName];
  4. self.themeColor=[UIColor parseColorFromStr:themeColorStr];
  5. self.themePath=[Bundle_Path_Of_ThemeResource stringByAppendingPathComponent:self.themeName];
  6. //init UI
  7. UIImage *navBarBackgroundImg=[[self themedImageWithName:@"themeColor.png"]
  8. resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 0.0f, 1.0f, 1.0f)
  9. resizingMode:UIImageResizingModeTile];
  10. [[UINavigationBar appearance] setBackgroundImage:navBarBackgroundImg
  11. forBarMetrics:UIBarMetricsDefault];
  12. }

这里从sqlite中获取了主题类型、主题颜色,然后配置了主题属性,同时初始化了一致的UINavigationBar。


在其他Controller中,获取图片的方式不再是:
  1. UIImage *img=[UIImage imageNamed:@"img.png"];

取而代之的是:

  1. UIImage *img=[[ThemeManager sharedInstance] themedImageWithName@"img.png"];

来确保img.png是来自当前主题文件夹下的img.png


实现如下:
  1. - (UIImage*)themedImageWithName:(NSString*)imgName{
  2. if (!imgName || [imgName isEqualToString:@""]) {
  3. return nil;
  4. }
  5. NSString *imgPath=[self.themePath stringByAppendingPathComponent:imgName];
  6. return [UIImage imageWithContentsOfFile:imgPath];
  7. }

到主题设置界面,选择一个新主题,会调用changeTheme方法:

  1. - (NSString *)changeTheme:(NSString*)themeName{
  2. if (!themeName || [themeName isEqualToString:@""]) {
  3. return nil;
  4. }
  5. NSString *themePath=[Bundle_Path_Of_ThemeResource stringByAppendingPathComponent:themeName];
  6. if (dirExistsAtPath(themePath)) {
  7. self.themePath=themePath;
  8. //update to db
  9. [ConfigItemDao set:[NSMutableDictionary dictionaryWithObjects:@[@"主题设置",themeName]
  10. forKeys:@[@"itemKey",@"itemValue"]]];
  11. //init again
  12. [self initCurrentTheme];
  13. }
  14. return themeName;
  15. }

这是一个简单的ThemeManager,通常有可能会有更多的配置,比如: themedFontWithName:(NSString *)fontName 等,当然方式都是一样的。

上面这些都只是定义,看看它是怎么运转的,怎么跟Controller组合的。

BaseController中:
注:BaseController是所有其他Controller的super class,任何时候,你去写一个应用程序也好,一个app也罢,你一开始总是应该规划好类型的继承关系,这是非常重要的,就个人经验而言,我总是会在创建一个应用程序之后,就立即构建一个super class,这会为你省去很多麻烦事。又废话了,进入正题。
在BaseController中,我们开放一个public method:
  1. - (void)configUIAppearance{
  2. NSLog(@"base config ui ");
  3. }

该类默认没有实现,主要用于供sub class去 override。

比如其中一个子controller的实现如下:
  1. - (void)configUIAppearance{
  2. self.appNameLbl.strokeColor=[[ThemeManager sharedInstance] themeColor];
  3. [self.commentBtn setBackgroundImage:[[ThemeManager sharedInstance] themedImageWithName:@"aboutBtnBG.png"]
  4. forState:UIControlStateNormal];
  5. [self.shareBtn setBackgroundImage:[[ThemeManager sharedInstance] themedImageWithName:@"aboutBtnBG.png"]
  6. forState:UIControlStateNormal];
  7. [self.developerBtn setBackgroundImage:[[ThemeManager sharedInstance] themedImageWithName:@"aboutBtnBG.png"] forState:UIControlStateNormal];
  8. [super configUIAppearance];
  9. }

可以看到,所有需要使用主题的UI控件的相关设置,都抽取出来放到了configUIAppearance中。

该方法,在所有子controller中都不会显式调用,因为在BaseController的viewDidLoad方法中以及调用了。这样,如果子类override了它,就会调用子类的,如果没有override,则调用BaseController的默认实现。


可以看到,上面的方法中配置了一些UI的外观,在一个view show出来的时候会被调用,还有一个调用点当然是主题改变的时候!
主题改变的时候,所有应用的controller无非是两种状态:
(1)未被实例化
(2)已经被实例化,而且view已经构建完成并且可见
对于第一种状态,我们不需要太多的担心,因为根据选择新主题的时候,会调用ThemeManager的changeTheme方法,该方法会update数据库的主题配置,同时init并config新的主题,所以未被实例化的controller在后面被实例化的时候,肯定会应用新的主题。
但对于已经可见的主题就不是第一种情况那样了,除非你重新show他们,否则是不会主动应用新的主题的,但将其他controller都distory之后再重新构建,根本不可能。所以,这里应用了ios的Notification,并再次展示了需要一个BaseController的好处,因为我们不需要为已存在的每一个controller注册消息通知并实现处理收到通知的方法,我们在BaseController中做,就等于在所有继承它的sub controller中做了,不是吗?
那么我们首先要在BaseController中像Notification center注册我们关注的Notification_For_ThemeChanged Notification:(在BaseController的ViewDidLoad中调用该注册方法)
  1. - (void)registerThemeChangedNotification{
  2. [Default_Notification_Center addObserver:self
  3. selector:@selector(handleThemeChangedNotification:)
  4. name:Notification_For_ThemeChanged
  5. object:nil];
  6. }

同时给出消息处理的逻辑:

  1. - (void)handleThemeChangedNotification:(NSNotification*)notification{
  2. UIImage *navBarBackgroundImg=[[[ThemeManager sharedInstance] themedImageWithName:@"themeColor.png"]
  3. resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 0.0f, 1.0f, 1.0f)
  4. resizingMode:UIImageResizingModeTile];
  5. [self.navigationController.navigationBar setBackgroundImage:navBarBackgroundImg
  6. forBarMetrics:UIBarMetricsDefault];
  7. <pre name="code" class="cpp">    [self configUIAppearance];</pre>}

可以看到这里又调用了configUIAppearance,由于继承关系,这里的self指针指向的并非BaseController实例(而是sub controller的实例),所以调用的也是sub controller的方法。所以,虽然可能还停留在“主题设置的界面”,但其他已存活的controller已经接受到了切换主题的Notification,并悄悄完成了切换。


最后再看看切换主题的大致逻辑:
  1. - (void)themeButton_touchUpIndise:(id)sender{
  2. //unselect
  3. UIButton *lastSelectedBtn=(UIButton*)[self.view viewWithTag:(Tag_Start_Index  + self.currentSelectedIndex)];
  4. lastSelectedBtn.selected=NO;
  5. //select
  6. UIButton *selectedBtn=(UIButton*)sender;
  7. self.currentSelectedIndex=selectedBtn.tag - Tag_Start_Index;
  8. selectedBtn.selected=YES;
  9. [[ThemeManager sharedInstance] changeTheme:((NSDictionary*)self.themeArr[self.currentSelectedIndex]).allKeys[0]];
  10. //post themechanged notification
  11. [Default_Notification_Center postNotificationName:Notification_For_ThemeChanged
  12. object:nil];
  13. }

大致的流程就是这样~


如果你觉得代码片段过于零散,没有关系,所有的实现代码都放到了github上。
并且整个应用都是开源的!