【问题标题】:How can I substitute the UITabBar of UITabBarController programmatically如何以编程方式替换 UITabBarController 的 UITabBar
【发布时间】:2018-05-13 10:21:38
【问题描述】:

由于以下问题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'

【问题讨论】:

    标签: ios uitabbarcontroller uitabbar


    【解决方案1】:

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

    class CustomTabBarController: UITabBarController {
        let customTabBar = CustomTabBar()
    
        override var tabBar: UITabBar {
            return customTabBar
        }
    }    
    

    【讨论】:

    • 这给了我以下错误:无法将“customTabBar.Type”类型的返回表达式转换为“UITabBar”类型。有什么想法吗?
    • 我认为覆盖 Tabbar 好像不起作用,我使用但没有任何结果。任何人都可以确认??
    • 您必须确保您的自定义标签栏类继承自UITabBar,否则将无法正常工作。
    • 我的 TabBar 项目在我应用覆盖后立即消失,即使返回 UITabBar() 本身也是如此
    • @Bruce 确保将 UITabBar 实例初始化为一个单独的变量并返回它。
    【解决方案2】:

    this answer 中给出了唯一可行的解​​决方案,方法是在UITabBarController 上使用setValue(:forKey:)

    【讨论】:

      【解决方案3】:

      您收到'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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-13
        • 2011-01-16
        • 2020-05-28
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多