ios - 如何通过以编程方式创建 UIImage 来更改 UITabBar 顶部边框的颜色?

标签 ios swift uiimage uitabbar

据我了解,更改顶部边框颜色的唯一方法是设置背景图像(320x49,像素线在顶部)。在我看来,这是唯一的方法(如果我错了请纠正我)。

有没有办法使用图像文件来做到这一点?例如,有人通过从代码创建 UIImage 来帮助我更改 NavigationBar 底部边框:

UINavigationBar.appearance().shadowImage = UIImage.colorForNavBar(UIColor.redColor())

extension UIImage {   
    class func colorForNavBar(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
}

这个解决方案实际上效果很好;它改变了我底部边框的颜色。

我尝试将其应用于 TabBar,但没有任何变化。

UITabBar.appearance().shadowImage = UIImage.colorForNavBar(.redColor())

最佳答案

您几乎已经回答了您自己的问题。您可以对 UITabBar 执行与对 UINavigationBar 执行的操作相同的操作。如果你想改变阴影图像(即“顶部边框”),那么你必须改变背景图像。直接来自Apple :

The custom shadow image for the tab bar. This attribute is ignored if the tab bar does not also have a custom background image. To set this attribute programmatically, use the shadowImage property.

在你自己的问题中你似乎意识到了这一点:

the only way to change the color of the top border is to set the background image (320x49, with pixel line at top)

除了顶部有一条线的不是背景图像。您只需将背景图像设置为任何内容,然后您就可以根据自己的喜好设置阴影图像。

如果您在 Xcode 中打开简单的“选项卡式应用程序”模板,您会发现添加这两行代码(以及您的 UIImage 扩展代码)确实有效:

// White background with red border on top
UITabBar.appearance().backgroundImage = UIImage.colorForNavBar(.whiteColor())
UITabBar.appearance().shadowImage = UIImage.colorForNavBar(.redColor())

Tab Bar

关于ios - 如何通过以编程方式创建 UIImage 来更改 UITabBar 顶部边框的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580148/

相关文章:

ios - Coredata float 变为零

ios - 来自 HealthKit 的数据最初丢失,然后当我重试时又出现 - 如何修复?

ios - 在 iOS 7 上纵向裁剪图像会导致方向不正确

ios - 来自 for in 数组的变量不会快速显示在我的 Collection View 中

ios - 如何检索和显示存储在数组中的 UIIMage?

ios - CoreData 阻塞 UI

ios - 如何将 UIButton 置于 TabBar 的前面?

objective-c - 在 Swift 中使用 PDFKIT 搜索 PDF

ios - UITableView 部分标题自动高度未正确更新

ios - 如何检测快速点击了哪个图像