简体   繁体   中英

How can I substitute the UITabBar of UITabBarController programmatically

I need to use a subclass of the UITabBar for my project because of the following problem Why page Push animation Tabbar moving up in the iPhone X .

I do not use storyboards. How can this be done programmatically?

-- update --

My CustomTabBarController.swift file now looks like this:

import UIKit

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

And my CustomTabBar.swift file looks like this:

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
        }
    }
}

But this gives me the following error:

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

You should create an instance of your custom tab bar and override the tabBar property inside your UITabBarController subclass with it.

class CustomTabBarController: UITabBarController {
    let customTabBar = CustomTabBar()

    override var tabBar: UITabBar {
        return customTabBar
    }
}    

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

The reason you're getting the 'customTabBar.Type' error is because you're returning the name of your class which, against normal convention, is camel cased. You want to be returning an object - an instance of your class - instead.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM