在结束我的问题之前,请注意,我已经知道.offset
,但是我只是找不到正确的用法。
我正在用SwiftUI开发一个简单的Music App,如下图所示,我想在图像上方放置一个简单的导航栏,同时覆盖了大部分内容。屏幕。为此,我使用了.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()
}
}
答案 0 :(得分:1)
SwiftUI将ZStack{}
用于分层视图。
很抱歉,现在是凌晨1点左右,我现在没有时间做更彻底的回答,但是我发现您3分钟前就处于活跃状态,这应该为您指明正确的方向。