ios - 如何在没有链接到 View Controller 的情况下快速创建标签栏项目

标签 ios swift uitabbarcontroller uitabbaritem

所以我的问题是我正在创建一个没有 Storyboard 的 UITabBarController,并且我对如何创建一个没有 Viewcontroller 的 UITabBar 项目感到困惑。因为我想要做的是我的 UITabBarItem 的第二项是一个不呈现 View Controller 的 Action 。

最佳答案

虽然我使用 Storyboard,但我在应用程序(关闭按钮)中实现了类似的功能。关闭按钮是一个 viewController,但我使用以下代码让它像普通按钮一样工作:

 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    // this provides UI feedback that the button has been pressed, even though it leads to the dismissal
        if viewController == self.viewControllers![4] {

           viewController.tabBarItem.image? = UIImage(named: "TabBarClose")!.imageWithColor(UIColor.red).withRenderingMode(UIImageRenderingMode.alwaysOriginal)

            return false
        } else {
        return true
        }
    }

override func viewDidDisappear(_ animated: Bool) {
//sets the close button back to original image
    self.viewControllers![4].tabBarItem.image = UIImage(named: "TabBarClose")!
}

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// this is so it never actually goes to the close buttons viewController
    currentTab = self.selectedIndex != 4 ? self.selectedIndex:currentTab
    saveTabIndexToPreferences(currentTab!)

}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    // assign functionality to the close button
    if item.tag == 100 {// this is old code, there is probably a better way to reference the tab
        dismissTabBar()
    } else {

    }        
}

编辑(对于被问到的问题)

func selectTabIndexFromPreferences() {
    let defaults:UserDefaults = UserDefaults.standard
    selectedIndex = defaults.integer(forKey: "songSelectionTabIndex_preference")
}

func saveTabIndexToPreferences(_ index:Int?) {
    if index != nil {
        let defaults:UserDefaults = UserDefaults.standard
        defaults.set(index!, forKey: "songSelectionTabIndex_preference")   
    }
}

tab-bar close button

关于ios - 如何在没有链接到 View Controller 的情况下快速创建标签栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45799041/

相关文章:

ios - CollectionView 单元格未加载到 View Controller 中

ios - Swift 中的圆形 UIBarButtonItems

iOS 将服务器时间转换为设备本地时间?

swift - 为什么调用 removeAtIndex : on a string invert the result if called within a string literal?

ios - Tableview 不重新加载数据

ios - 如何获取 UIStoryBoard segued UITabbarController 引用

ios - customFooterView 内的 UISwitch 需要调用使用 Swift 声明的类外部的方法

iphone - 如何在 xcode 4.3 lion 中查找将调用函数而不是搜索工具的位置

ios - Swift 使用动态高度以编程方式创建 UIButton

ios - UITabBarController 没有响应