我正在使用 SwiftUI 邁出第一步,但根據條件顯示的組件出現問題。
我正在嘗試顯示全屏彈出視窗(全屏,半透明黑色背景,中間的彈出視窗帶有白色背景)。為了實作這一點,我制作了這個組件:
struct CustomUiPopup: View {
var body: some View {
ZStack {
}
.overlay(CustomUiPopupOverlay, alignment: .top)
.zIndex(1)
}
private var CustomUiPopupOverlay: some View {
ZStack {
Spacer()
ZStack {
Text("POPUP")
.padding()
}
.zIndex(1)
.frame(width: UIScreen.main.bounds.size.width - 66)
.background(Color.white)
.cornerRadius(8)
Spacer()
}
.frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
.background(Color.black.opacity(0.6))
}
}
如果我在我的主視圖中設定它,彈出視窗會正確顯示在按鈕上:
struct MainView: View {
var body: some View {
CustomUiPopup()
Button("Click to show popup") {
print("click on button")
}
}
}
如果我設定了這個,我的彈出視窗不會顯示(正確,因為 hasToShowPopup 是假的),但如果我點擊按鈕失敗,彈出視窗不會顯示并且無法再次點擊按鈕(?!),看起來像視圖被凍結。
struct MainView: View {
@State private var hasToShowPopup = false
var body: some View {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
我什至嘗試將 hasToShowPopup 初始化為 true 但彈出視窗一直失敗,它首先沒有顯示:
struct MainView: View {
@State private var hasToShowPopup = true
var body: some View {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
所以我的結論是,我不知道為什么,但是如果我將我的 CustomUiPopup 放在“if”中,則某些東西不會正確呈現。
我的代碼有什么問題?
無論如何,如果這不是顯示彈出視窗的正確方法,我很樂意提供任何建議。
遵循 Ptit Xav 的建議,我嘗試了相同的結果(我的 CustomUiPopup 沒有顯示):
struct MainView: View {
@State private var hasToShowPopup = false
var body: some View {
VStack {
if hasToShowPopup {
CustomUiPopup()
}
Button("Click to show popup") {
hasToShowPopup = true
}
}
}
}
uj5u.com熱心網友回復:
這對我很好:
struct CustomUiPopup: View {
var body: some View {
ZStack {
Spacer()
Text("POPUP")
.padding()
.zIndex(1)
.frame(width: UIScreen.main.bounds.size.width - 66)
.background(Color.white)
.cornerRadius(8)
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(
Color.black.opacity(0.6)
.ignoresSafeArea()
)
}
}
struct ContentView: View {
@State private var hasToShowPopup = false
var body: some View {
ZStack {
Button("Click to show popup") {
hasToShowPopup = true
}
if hasToShowPopup {
CustomUiPopup()
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497340.html
上一篇:SwiftUI-我無法在螢屏上更改Picker文本的樣式
下一篇:“Int”型別的值沒有成員“秒”
