I have a dropdown menu that acts a little weird, see here.
The text updates step by step, not instantaneously, and it quivers for a little bit after being updated.
Here is the relevant code:
The state variables used
@State private var gender = ""
@State private var birthDate = Date.now
@State private var formattedDate = ""
@State private var genderMenuTitle = "Gender"
The Form where the dropdown menu lies:
Form {
Section(header: Text("Gender")) {
Menu(genderMenuTitle) {
Button (action: {
gender = "F"
genderMenuTitle = "Female"
print(gender)
}, label: {
Text("Female")
})
Button (action: {
gender = "M"
genderMenuTitle = "Male"
print(gender)
}, label: {
Text("Male")
})
Button (action: {
gender = "O"
genderMenuTitle = "Other"
print(gender)
}, label: {
Text("Other")
})
Button (action: {
gender = "?"
genderMenuTitle = "Rather not say"
print(gender)
}, label: {
Text("Rather not say")
})
}
}
Why is this happening?
2
Answers
Because you’re manually updating your view every-time a user clicks the button, you can make this process smoother by using a
withAnimation
closure.But I would recommend you to just use a picker instead.
It isn’t you particularly, but if you have a
Menu
where you change the title, which is typical, don’t use the initializerinit(_ titleKey: LocalizedStringKey, @ViewBuilder content: () -> Content) where Label == Text
rather useinit(@ViewBuilder content: () -> Content, @ViewBuilder label: () -> Label)
like below. I also simplified things by using anenum
to reduce the amount of state tracking: