换肤-基础 - (Swift)

之前写了几篇OC中换肤的功能介绍,这里使用Swift封装了一个工具类,简单实现了根据当前皮肤状态切换图片的效果

import UIKit

class ChangeSkinTool: NSObject {
    
    // 全局访问点
    static let sharedTool: ChangeSkinTool = ChangeSkinTool()
    
    private var isNight: Bool = false
    
    override init() {
        super.init()
        
       isNight = NSUserDefaults.standardUserDefaults().boolForKey("isNightMode")
        
    }
    
    
    // 根据皮肤设置图片
    func setImageByCurrentSkin (imageName: String) -> UIImage {
        
        var name: String = imageName
        if isNight {
            
            name = "\(imageName)_night"
        }
        return UIImage(named: name)!
        
    }
    
    // 返回当前皮肤状态
    func currentSkin() -> Bool {
        return isNight
    }
    
    // 保存当前皮肤状态
    func saveCurrentSkinMode(isNightMode: Bool) -> Void {
        
        isNight = isNightMode
        // 本地化
        NSUserDefaults.standardUserDefaults().setBool(isNightMode, forKey: "isNightMode")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

}

与之前OC版本原理一直,外界使用示例代码:

    @IBOutlet weak var isNigthSwitch: UISwitch!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    private func setupUI () -> Void{
        
        isNigthSwitch.on = ChangeSkinTool.sharedTool.currentSkin()
        
        firstImageView.image = ChangeSkinTool.sharedTool.setImageByCurrentSkin("girl")
        
    }
    
    
    @IBAction func isNightSwitchClick(sender: UISwitch) {
        
        // 保存皮肤状态
        ChangeSkinTool.sharedTool.saveCurrentSkinMode(sender.on)
        
        firstImageView.image = ChangeSkinTool.sharedTool.setImageByCurrentSkin("girl")
        
    }

你可能感兴趣的:(换肤-基础 - (Swift))