如何以编程方式替换UITabBarController的UITabBar

时间:2017-11-29 16:24:16

标签: ios uitabbarcontroller uitabbar

由于以下问题Why page Push animation Tabbar moving up in the iPhone X,我需要为我的项目使用UITabBar的子类。

我不使用故事板。如何以编程方式完成?

- 更新 -

我的CustomTabBarController.swift文件现在看起来像这样:

import UIKit

@objc class customTabBarController: UITabBarController {
    override var tabBar: UITabBar {
        return customTabBar
    }
}

我的CustomTabBar.swift文件如下所示:

import UIKit

class customTabBar: UITabBar {

    override var frame: CGRect {
        get {
            return super.frame
        }
        set {
            var tmp = newValue
            if let superview = superview, tmp.maxY !=
                superview.frame.height {
                tmp.origin.y = superview.frame.height - tmp.height
            }

            super.frame = tmp
        }
    }
}

但是这给了我以下错误:

Cannot convert return expression of type 'customTabBar.Type' to return type 'UITabBar'

3 个答案:

答案 0 :(得分:4)

您应该创建自定义标签栏的实例,并使用它覆盖UITabBarController子类中的tabBar属性。

class CustomTabBarController: UITabBarController {
    let customTabBar = CustomTabBar()

    override var tabBar: UITabBar {
        return customTabBar
    }
}    

答案 1 :(得分:0)

出现'customTabBar.Type'错误的原因是因为您返回的类名是驼峰式的,这是违反常规的。您想返回一个 object -类的实例-

import UIKit

@objc class customTabBarController: UITabBarController {
    let myCustomTabBar = customTabBar() // If we're writing conventional swift,
                                        // this should be CustomTabBar()
    
    override var tabBar: UITabBar {
        // Because your class name is customTabBar instead of CustomTabBar,
        // this is returning a TYPE instead of an OBJECT
        // return customTabBar

        // If you wanted to return a new version of a tab bar on every
        // get of this object, you'd use the following code which is similar to yours:
        // return customTabBar()

        // More likely, you want to return the SAME tabBar throughout this object's
        // lifecycle.
        return myCustomTabBar
    }
}

答案 2 :(得分:0)

this answer 中通过在 setValue(:forKey:) 上使用 UITabBarController 给出了唯一有效的解决方案。