UITabBar 背景图像的图像缩放

image scaling for UITabBar background image

我已经在我的应用程序中创建了 UITabBarController。

然后在 viewDidLoad() 我想更改 UITabBar 背景图像。这是我试图让它工作的代码:

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UITabBar.appearance().translucent = false
        UITabBar.appearance().backgroundColor = UIColor.clearColor()
        UITabBar.appearance().backgroundImage = UIImage(named: "tabbar_background")
        UITabBar.appearance().contentMode = .ScaleAspectFit
    }
}

但结果不正确 (image)。有人可以帮我让它填满整个标签栏框架吗?

尝试将 image 调整为标签栏大小。或将 imageView 添加到 tabBar 作为 subview,然后使用 imageView 中的图像。

子类 TabBarController 并在其中添加 imageview

var bgView: UIImageView = UIImageView(image: UIImage(named: "tabBarBackground.png"))
bgView.frame = CGRectMake(0, 420, 320, 60)//you might need to modify this frame to your tabbar frame
self.view.addSubview(bgView)

这是带有自定义图标的自定义半透明标签栏图像的代码。您将需要通过变量直接引用标签栏。

Swift 3

private func setupTabBar() {
    print ("Setting up the Tab Bar and Items")

    tabBarView.clipsToBounds = true
    tabBarView.backgroundImage = UIImage()

    let bgView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "TabBarBackground"))
    bgView.frame = tabBarView.bounds
    tabBarView.addSubview(bgView)

    tabBarView.tintColor = UIColor.white
    UITabBar.appearance().tintColor = UIColor.gray
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.gray], for: .selected)

    tabBarLimitsItemView.image      = #imageLiteral(resourceName: "TabIconLimits").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
    tabBarControlsItemView.image    = #imageLiteral(resourceName: "TabIconControls").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
    tabBarPayRulesItemView.image    = #imageLiteral(resourceName: "TabIconPayRules").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
    tabBarSettingsItemView.image    = #imageLiteral(resourceName: "TabIconSettings").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}

这对我有用 swift 3

class MyTabBarController: UITabBarController, UINavigationControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    let backgroundImage = UIImageView(image: UIImage(named: "gray background"))
    backgroundImage.frame = backgroundImage.bounds
    self.view.addSubview(backgroundImage)


}

我使用 clipsToBounds 解决了这个问题。
这是我的例子:

let tabBar = self.tabBar
tabBar.backgroundImage = UIImage()
tabBar.clipsToBounds = true

这在 iPhone X

上完美运行