缓存和还原TabBarItem顺序

时间:2019-03-22 19:36:38

标签: swift

在用户修改了原始顺序之后,是否有一种简单的方法可以对UITabBarController执行此操作?我可以使用以下代码,但感觉有些笨拙。

class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.restoreItemOrder()
    }

    override func tabBar(_ tabBar: UITabBar, didEndCustomizing items: [UITabBarItem], changed: Bool) {

        if changed {
            self.cacheItemOrder(items: items)
        }
    }
}

编辑后缓存/恢复订单的扩展名。

extension UITabBarController {

    private static let cacheKey = "tabBarIndex"

    public func cacheItemOrder(items: [UITabBarItem]) {
        var index = [String: Int]()
        var i = 0

        for item in items {
            if let title = item.title {
                index[title] = i
            }

            i += 1
        }

        UserDefaults.standard.set(index, forKey: UITabBarController.cacheKey)
    }

    public func restoreItemOrder() {
        if let dict = UserDefaults.standard.dictionary(forKey: UITabBarController.cacheKey) as? [String: Int] {

            if let vcs = self.viewControllers {

                self.viewControllers = vcs.sorted() {
                    var idx0 = 99
                    var idx1 = 99

                    if let t0 = $0.tabBarItem.title, let idx = dict[t0] {
                        idx0 = idx
                    }
                    if let t1 = $1.tabBarItem.title, let idx = dict[t1] {
                        idx1 = idx
                    }

                    return idx0 < idx1
                }  
            }
        }
    }
}

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用功能性习语更简洁地表达一切:

extension UITabBarController {

    private static let cacheKey = "tabBarIndex"

    public func cacheItemOrder(items: [UITabBarItem]) {
        UserDefaults.standard.set(
            [String: Int](uniqueKeysWithValues: items.enumerated().map { ($1.title ?? "", $0)}),
            forKey: UITabBarController.cacheKey
        )
    }

    public func restoreItemOrder() {
        guard let order = UserDefaults.standard.dictionary(forKey: UITabBarController.cacheKey) as? [String: Int] else {
            return
        }
        viewControllers?.sort { left, right in
            guard let leftIndex = left.title.flatMap({order[$0]}),
                  let rightIndex = right.title.flatMap({order[$0]}) else {
                return false
            }
            return leftIndex < rightIndex
        }
    }
}