[转] SwiftUI实现Apple Music的“Now Playing Bar”效果

参考链接: https://itnext.io/add-a-now-playing-bar-with-swiftui-to-your-app-d515b03f05e3

3周前 35次点击 来自 移动端

标签: SwiftUI

视图的整体结构比较简单,基于ZStack在顶层悬浮显示“Now Playing Bar”即可

1. 底层视图

TabView(selection: $selection) {
    ListenNowView().tag(0).tabItem { Label("Listen Now", systemImage: "play.circle.fill") }
    BrowseView().tag(1).tabItem { Label("Browse", systemImage: "square.grid.2x2.fill") }
    RadioView().tag(2).tabItem { Label("Radio", systemImage: "dot.radiowaves.left.and.right") }
    LibraryView().tag(3).tabItem { Label("Library", systemImage: "square.stack") }
    SearchView().tag(4).tabItem { Label("Search", systemImage: "magnifyingglass") }
}

2. Now Playing Bar

struct NowPlayingBar<Content: View>: View {
    var content: Content
    
    @ViewBuilder var body: some View {
        ZStack(alignment: .bottom) {
            content
            // Now playing bar
        }
    }
}

在底层视图上悬浮显示

NowPlayingBar(content: ListenNowView()).tag(0).tabItem { Label("Listen Now", systemImage: "play.circle.fill") }

3. 添加背景玻璃模糊效果

SwiftUI没有提供Blur效果,调用使用UIKit

struct Blur: UIViewRepresentable {
    var style: UIBlurEffect.Style = .systemChromeMaterial
    
    func makeUIView(context: Context) -> UIVisualEffectView {
        return UIVisualEffectView(effect: UIBlurEffect(style: style))
    }
    
    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
        uiView.effect = UIBlurEffect(style: style)
    }
}

嵌入背景效果

ZStack {
    Rectangle().foregroundColor(Color.white.opacity(0.0)).frame(width: UIScreen.main.bounds.size.width, height: 65).background(B
    HStack {
        Button(action: {}) {
            HStack {
                Image("Cover").resizable().frame(width: 45, height: 45).shadow(radius: 6, x: 0, y: 3).padding(.leading)
                Text("Shake It Off").padding(.leading, 10)
                Spacer()
            }
        }.buttonStyle(PlainButtonStyle())
        Button(action: {}) {
            Image(systemName: "play.fill").font(.title3)
        }.buttonStyle(PlainButtonStyle()).padding(.horizontal)
        Button(action: {}) {
            Image(systemName: "forward.fill").font(.title3)
        }.buttonStyle(PlainButtonStyle()).padding(.trailing, 30)
    }
}

最后效果大概长这样

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1