首页 > 解决方案 > 如何控制 UITabBar selectedIndicatorImage 的高度

问题描述

我正在尝试设置我的样式,tabBar.selectedIndicatorImageUITabBar无法正确定位。它应该是 50 像素高并与给定选项卡的顶部对齐。但是,它与底部对齐:

在此处输入图像描述

class MenuTabBarController: UITabBarController {

    override func viewDidLoad() {
      super.viewDidLoad()

      setTabs()

      styleTabBar()

    }
      func setTabs() {
    let tab1 = GradientNavigationController(rootViewController: FeedViewController())
    let tab2 = GradientNavigationController(rootViewController: NotificationsTableViewController())
    let tab3 = GradientNavigationController(rootViewController: SearchViewController())
    let tab4 = GradientNavigationController(rootViewController: CallsTableViewController())
    UITabBarController().setViewControllers([tab1, tab2, tab3, tab4], animated: false)
  }

    // UITabBarDelegate
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
      if item.tag == 0 { 
        if let feedNav = children[0] as? UINavigationController, let feedVC = feedNav.viewControllers[0] as? FeedViewController {
          feedVC.tableView.reloadData()
        }
      }
    }

    func styleTabBar() {
      // Set the tab bar separator
      UITabBar.appearance().shadowImage = UIImage.colorForNavBar(color:.white) //This sets the TabBar top separator color
    }

    override func viewDidAppear(_ animated: Bool) {
      let numberOfItems = CGFloat(tabBar.items!.count)
      let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: 50)
      let selectionBackgroundImage = UIImage.imageWithColor(color: .lightGrey3, size: tabBarItemSize)
      selectionBackgroundImage.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), resizingMode: .tile)
      tabBar.selectionIndicatorImage = selectionBackgroundImage
    }
}

UIImage 扩展:

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

我最接近甚至影响图像位置的方法是通过更改扩展CGRect中的原点:UIImage

let rect: CGRect = CGRect(x: 0, y: -25, width: size.width, height: size.height)

在此处输入图像描述

但这似乎只是降低了我需要保持在 50px 的图像的高度。

我在 SO 上发现了很多关于此的主题,这就是我走到这一步的方式,但我没有发现任何东西可以解决这个问题。

标签: iosswiftuitabbar

解决方案


推荐阅读