Swift Theme Color Top solution

Source: Internet
Author: User

One, the general theme color point of use
The app will set its theme color before publishing to unify the style of the app (there may be multiple sets of topics). There are several aspects to the theme color setting, as follows:
1.TabBar section, set picture highlighting, text height color
2.NavigationBar section, set the navigation bar color and font color
3. Apply tags, etc., set the color of the font
4. Apply Picture Theme Color


Theme color set point, roughly from the above four aspects, the color of the theme of the picture we can be processed by the way the picture is changed. The ' 1-3 ' bar, which is handled by code, has different processing methods. We have the following general methods:


Step One: Change separation
1. Expand Uicolor with the swift extension syntax to apply theme colors uniformly in the extension (for a single theme color)
2. Write the configuration of the theme color to the file, which is parsed by the corresponding logic. This method encapsulates the theme color logic into a theme-color management class (for multiple sets of topics)

Step two: Discrete classes with step-up encapsulation
1. In any place using the theme color, use the Uicolor method in the extension to set, generally including background color, text color, etc.

This gives an extension of the Uicolor
Extension Uicolor {        //Theme Color    class func Applicationmaincolor () uicolor {        return Uicolor (red:238/255, green:64/255, blue:86/255, alpha:1)    }        //second theme Color    class func Applicationsecondcolor (), Uicolor {        Return Uicolor.lightgraycolor ()    }        //Warning Color    class func Applicationwarningcolor (), Uicolor {        Return Uicolor (red:0.1, Green:1, blue:0, alpha:1)    }        //link color    class func Applicationlinkcolor () Uico lor {        return Uicolor (red:59/255, green:89/255, blue:152/255, alpha:1)    }    }





second, Tabbar theme color settings
In many applications, the Tabbar control is used by default, but settings such as Tabbar theme color are different depending on usage. Code creation is more flexible, and changing the theme color is easier. The use of Xib/storyboard is also a way to do a unified processing, such as the following, iteration change tabbar default font color
Func Configtabbar () {Let        items = Self.tabBar.items for item in items ' as        [Uitabbaritem] {let            dic = Nsdictiona Ry (Object:UIColor.applicationMainColor (),             forkey:nsforegroundcolorattributename)            Item.settitletextattributes (DIC,              forState:UIControlState.Selected)        }    }




Set Tabbar picture and text default check color
Self.tabBar.selectedImageTintColor = Uicolor.applicationmaincolor ()


Tips Notes > Changing this property's value provides visual feedback in the user interface, including the running of any Associated animations. The selected item displays the tab bar item ' s selectedimage image, using the tab bar ' s Selectedimagetintcolor value. To prevent system coloring of a item, provide images using the Uiimagerenderingmodealwaysoriginal rendering mode.


In some cases, when the normal status is a white picture, when the real machine is tested, the white picture will appear biased (the result is grayed out), due to system default coloring, when creating Uitabbaritem, Can be avoided by using uiimagerenderingmodealwaysoriginal. The sample code is as follows:

Let Imagenormal = UIImage (contentsoffile: "Imagenormal")? Imagewithrenderingmode (uiimagerenderingmode.alwaysoriginal) Let imageselected = UIImage (contentsoffile: " Imageselected ") Let Tabbaritem = Uitabbaritem (title:" title ",         Image:imagenormal,         selectedimage: imageselected)

three, once and for all, using hook principle to set Navigationbar color


iOS app, Navigationbar is very popular, its use mainly includes the following two scenes
1. Direct Code Building
2.xib/storyboard Construction
If it is purely code-building, it is relatively simple to use the Uicolor extension to set the color directly. In the actual project, some interfaces are created by Xib/storyboard, some are written by code, but this is difficult for everyone to use inheritance. Create a subclass that inherits from Uinavigationcontroller, and use this subclass to set the theme color uniformly. Then tell everyone in the project to force the use of the Uinavigationcontroller subclass, including Xib/storyboard. The question is, what about the old project, this mandatory requirement can work, there is no better way to let everyone normal use of uinavigationcontroller, and in the case of the unknown, the establishment of all navigationbar it?
Code first, then explain.
1. Create an uiviewcontroller extension
Extension Uiviewcontroller {    func viewdidloadforchangetitlecolor () {        self.viewdidloadforchangetitlecolor ()        if Self.iskindofclass (Uinavigationcontroller.classforcoder ()) {           Self.changenavigationbartextcolor (self As Uinavigationcontroller)        }    }        func Changenavigationbartextcolor (navcontroller: Uinavigationcontroller) {Let        nav = Navcontroller as Uinavigationcontroller let        dic = Nsdictionary (object: Uicolor.applicationmaincolor (),         forkey:nsforegroundcolorattributename)        Nav.navigationBar.titleTextAttributes = dic        Nav.navigationBar.barTintColor = Uicolor.applicationsecondcolor ()        Nav.navigationBar.tintColor = Uicolor.applicationmaincolor ()            }  }

2. Writing tool classes for hooks
Func Swizzlingmethod (Clzz:anyclass, #oldSelector: Selector, #newSelector: Selector) {let    Oldmethod = Class_ Getinstancemethod (Clzz, oldselector) let    newmethod = Class_getinstancemethod (clzz, newselector)    Method_ Exchangeimplementations (Oldmethod, Newmethod)}


3. Calling in Appdelegate
  Func application (application:uiapplication, Didfinishlaunchingwithoptions launchoptions:nsdictionary?), Bool { C5/>swizzlingmethod (uiviewcontroller.self,         oldselector: "Viewdidload",         newselector: " Viewdidloadforchangetitlecolor ")//do others        return True    }
4. Explanation of the principleAt the entrance of the program, through the runtime mechanism, the dynamic replacement of the Uiviewcontroller cycle method Viewdidload for the method we specify Viewdidloadforchangetitlecolor. In Viewdidloadchangetitlecolor, two things need to be done:

* Call the original Viewdidload method
* Perform modified theme color related code

How to call the original Viewdidload method

In Appdelegate, by calling the method ' Swizzlingmethod ' We replace the viewdidload with the Viewdidloadforchangetitlecolor method body, which is the principle of:





As can be seen from the figure above, when executing in Viewdidloadforchangetitlecolor:
Self.viewdidloadforchangetitlecolor ()
is not to cause a circular call, but rather to invoke the Viewdidload method body that we expect to execute.


third, the treatment of Xib/storyboard
Some of the theme colors set in Xib/storyboard, such as text color, button highlighting color, and so on, how to deal with it, take Uilabel as an example, to establish an extension
Extension UILabel {    var colorstring:string {        Set (newvalue) {            switch newvalue {case            "main":                Self.textcolor = Uicolor.applicationmaincolor () Case            "second":                Self.textcolor = Uicolor.applicationsecondcolor () Case            "Warning":                self.textcolor = Uicolor.applicationwarningcolor ()            Default:                Self.textcolor = Uicolor.applicationsecondcolor ()            }        }        get {            return Self.colorstring        }}}    



Edit in Xib/storyboard's inspector, such as:


4. Summary



1. Only a set of themes, the above method can be copied directly, when changing the theme, only need to change the corresponding picture and modify the Uicolor extension class


2. When there are multiple sets of themes, users can freely switch themes, can be viewwillappear by the hook mechanism in the article, can also easily achieve the theme changes

Swift Theme Color Top solution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.