【问题标题】:select tabbar item programmatically and show the indicator image以编程方式选择标签栏项目并显示指示器图像
【发布时间】:2017-11-12 14:41:44
【问题描述】:

我使用的是 UITabBar,而不是 UITabBarController。每当用户单击任何选项卡时,我都能看到带下划线的图像。

public override func viewDidLoad() {
    super.viewDidLoad()
    UITabBar.appearance().selectionIndicatorImage = getImageWithColorPosition(color: UIColor.darkGray, size: CGSize(width:presenterView.frame.size.width/2, height:49), lineSize: CGSize(width:presenterView.frame.size.width/2, height:2))
}

//getImageWithColorPosition用于在UITabBarItem下方添加下划线的图片

func getImageWithColorPosition(color: UIColor, size: CGSize, lineSize: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    let rectLine = CGRect(x: 0, y: size.height-lineSize.height, width: lineSize.width, height: lineSize.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    UIColor.clear.setFill()
    UIRectFill(rect)
    color.setFill()
    UIRectFill(rectLine)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    openItem1()
}

public func  tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if (item.tag == 0) {
        openItem1()
    } else {
        openItem2()
    }
}

但是,当用户单击任何选项卡项时,只会显示带下划线的图像。当用户第一次登陆屏幕时,我想选择一个默认选项卡。当我以编程方式执行此操作时,下划线图像不会出现。我阅读了几篇堆栈溢出帖子,其中说 UITabBar 上的选择不能以编程方式触发。

还有其他方法吗?

【问题讨论】:

    标签: swift uiviewcontroller uitabbar uitabbaritem


    【解决方案1】:

    如果我正确理解了这个问题,您希望在用户打开应用程序时以编程方式在您的 UITabBar 上选择一个标签。您可以在AppDelegate 中执行此操作,例如在didFinishLaunchingWithOptions

    在我的项目中,我会根据某些通知等事件跳转到标签栏控制器中的标签。在AppDelegate 内部,我使用以下代码以编程方式选择一个选项卡:

    if let tabbarController = self.window?.rootViewController as? UITabBarController {
        tabbarController.selectedIndex = 0
    }
    

    默认情况下,如果应用是从冷启动启动的并且最后打开的选项卡(如果应用之前已启动并保留在应用切换器中),则所选项目将是索引为 0 的项目。

    希望这是您正在寻找的。​​p>

    【讨论】:

      猜你喜欢
      • 2014-06-21
      • 2012-02-11
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 2018-02-11
      相关资源
      最近更新 更多