以编程方式选择选项卡栏项并显示指示器图像



我使用的是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 上的选择不能以编程方式触发。

还有其他方法吗?

如果我

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

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

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

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

希望这就是你要找的。

最新更新