触发UITabBarController按钮上的图像选择器

时间:2018-10-15 04:03:45

标签: ios swift uitabbarcontroller

我在tabbar中制作了一个storyboard,其中包含4个条形项目,通过右键单击并设置viewcontroller segue将它们全部连接到其他视图控制器。现在,对于第二个按钮,我想显示imagepicker而不是viewcontroller。当我从UITabBarController的情节提要中删除第二个segue时,我的第四个栏项消失了。

这是我的tabview控制器

class BaseTabBarController: UITabBarController, UITabBarControllerDelegate {
    let arrayOfImageNameForUnselectedState = ["home", "explore", "addIcon", "notification", "accountIcon"]
    let arrayOfImageNameForSelectedState = ["homeFilled", "exploreFilled", "addIcon", "notificaitonFilled", "accountIcon"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self

        if let count = self.tabBar.items?.count {
            for i in 0..<count {
                let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
                let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]

                self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
                self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
            }
        }

    }

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

        if tabBar.items?.index(of: item) ?? 0 == 2 {
            //Clicked add tab, cancel segue and show imagepicker
        } else {
            selectedTabindex = tabBar.items?.index(of: item) ?? 0
        }
    }
}

如何在第二栏按钮单击时显示图像选择器

1 个答案:

答案 0 :(得分:2)

不要从情节提要中删除Second segue,将虚拟视图控制器显示在选项卡栏中的选项卡按钮。在UITabBarController的子类中实现UITabBarController控制器的委托方法,并在第二个viewcontroller的shouldSelect方法中返回false,并在那里显示ImagePicker View。

代码:

class BaseTabBarController : UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }

}

extension BaseTabBarController : UITabBarControllerDelegate {

    func  tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if self.viewControllers?.index(of:viewController) == 1 {
            // TO Do code for Image Picker and Present it 
            return false
        } else {
            return true
        }
    }

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {

    }

}