[英]Place view on top of others SwiftUI
請在結束我的問題之前,請注意我已經知道.offset
,但我找不到正確的使用方法。
我正在 SwiftUI 中開發一個簡單的音樂應用程序,如下圖所示,我想在圖像頂部放置一個簡單的導航欄,同時覆蓋屏幕的很大一部分。 為了實現這一點,我使用.offset
並將其放置在(UIScreen.main.bounds.size.height / 2) * -1
上,使其位於頂部,但這只會導致其他元素的非常奇怪的行為,例如滾動視圖而不是工作,元素相互剪輯等。
有沒有更清潔和更好的方法來實現這一目標? 我使用.offset()
錯了嗎?
提前致謝
我的代碼
ContentView.swift
import SwiftUI
enum SelectedView: Int, CaseIterable {
case liked = 0
case recent = 1
case top = 2
}
struct MenuView: View {
@State var selectedView: SelectedView
var body: some View {
HStack {
Spacer()
MenuButton(view: .liked, isSelected: false)
Spacer()
MenuButton(view: .recent, isSelected: false)
Spacer()
MenuButton(view: .top, isSelected: false)
Spacer()
}.foregroundColor(Color(UIColor(named: "inversedAdaptiveColor")!))
.font(.headline)
.background(RoundedRectangle(cornerRadius: 100)
.frame(height: 80)
.foregroundColor(Color(UIColor(named: "adaptiveColor")!))
)
}
func getSelectedView(x: SelectedView) -> MenuButton {
if x == selectedView {
return MenuButton(view: x, isSelected: true)
} else {
return MenuButton(view: x, isSelected: false)
}
}
}
struct MenuButton: View {
let view: SelectedView
@State var isSelected: Bool = false
var body: some View {
Button(action: {
self.isSelected.toggle()
}) {
if view == .liked {
Text("Liked")
.overlay( isSelected ?
AnyView (
Circle()
.frame(width: 5, height: 5)
.padding(.top, 40))
: AnyView(Spacer())
)
} else if view == .recent {
Text("Recent")
.overlay( isSelected ?
AnyView (
Circle()
.frame(width: 5, height: 5)
.padding(.top, 40))
: AnyView(Spacer())
)
} else {
Text("Top")
.overlay( isSelected ?
AnyView (
Circle()
.frame(width: 5, height: 5)
.padding(.top, 40))
: AnyView(Spacer())
)
}
}
}
}
struct HomeView: View {
var body: some View {
VStack {
TopMainView()
Spacer()
ScrollView {
MenuView(selectedView: .liked)
.padding(.vertical, 50)
SongView(title: "Doesn't Matter", author: "Akon", artwork: "misician2", darkInterface: false, type: .outside)
SongView(title: "Doesn't Matter", author: "Akon", artwork: "misician2", darkInterface: false, type: .outside)
SongView(title: "Doesn't Matter", author: "Akon", artwork: "misician2", darkInterface: false, type: .outside)
}.padding().padding(.top, -150)
.frame(height: (UIScreen.main.bounds.height / 2) - 200)
NowPlayingView()
}.edgesIgnoringSafeArea(.bottom)
}
}
struct TopMainView: View {
@State var opacity: Double = 0.0
var body: some View {
VStack {
Image("misician2")
.resizable()
.frame(height: (UIScreen.main.bounds.size.height / 2) - 20)
.cornerRadius(50, corners: [.bottomLeft, .bottomRight])
.edgesIgnoringSafeArea(.top)
TransparentNavigationView(view: .home)
.padding(.horizontal, 30)
.offset(y: (UIScreen.main.bounds.size.height / 2) * -1)
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
SwiftUI 將ZStack{}
用於分層視圖。
很抱歉,現在快凌晨 1 點了,我現在沒有時間進行更全面的回答,但我看到您在 3 分鍾前還很活躍,這應該會為您指明正確的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.