Ell*_*ogo 11 shadow swift swiftui swiftui-tabview
我正在尝试在 SwiftUI 中实现 TabView,它与屏幕背景具有相同的颜色,但上面还有一个阴影,如下图所示:

到目前为止我已经能够正确显示颜色,但我不知道如何添加阴影。这是我的代码:
struct ContentView: View {
init() {
let appearance = UITabBarAppearance()
appearance.configureWithTransparentBackground()
UITabBar.appearance().standardAppearance = appearance
}
var body: some View {
TabView {
Text("First View")
.tabItem {
Image(systemName: "square.and.arrow.down")
Text("First")
}
Text("Second View")
.tabItem {
Image(systemName: "square.and.arrow.up")
Text("Second")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何做到这一点?我将不胜感激你的帮助:)
Ell*_*ogo 15
我找到了解决方案。您可以创建自己的阴影图像并将其添加到 UITabBar 外观,如下所示:
// load your custom shadow image
let shadowImage: UIImage = ...
//you also need to set backgroundImage, without it shadowImage is ignored
UITabBar.appearance().backgroundImage = UIImage()
UITabBar.appearance().shadowImage = shadowImage
Run Code Online (Sandbox Code Playgroud)
请注意,通过设置
UITabBar.appearance().backgroundImage = UIImage()
Run Code Online (Sandbox Code Playgroud)
您使 TabView 透明,因此如果您的内容可以在其下方滚动,则这并不理想。为了解决这个问题,您可以设置 TabView 的颜色。
let appearance = UITabBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = UIColor.systemGray6
UITabBar.appearance().standardAppearance = appearance
Run Code Online (Sandbox Code Playgroud)
我想以编程方式生成阴影图像。为此,我创建了 UIImage 的扩展。(代码取自这里)
extension UIImage {
static func gradientImageWithBounds(bounds: CGRect, colors: [CGColor]) -> UIImage {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = colors
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Run Code Online (Sandbox Code Playgroud)
最后我将 TabView 的样式设置为这样:
let image = UIImage.gradientImageWithBounds(
bounds: CGRect( x: 0, y: 0, width: UIScreen.main.scale, height: 8),
colors: [
UIColor.clear.cgColor,
UIColor.black.withAlphaComponent(0.1).cgColor
]
)
let appearance = UITabBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = UIColor.systemGray6
appearance.backgroundImage = UIImage()
appearance.shadowImage = image
UITabBar.appearance().standardAppearance = appearance
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4032 次 |
| 最近记录: |