Strange behaviour with Pickers and Forms in SwiftUI - swiftui

I'm developing an application in SwiftUI to manage a virtual datacenter (servers, firewall rules, load balancers...) The code I attach is an excerpt of the app to show the current problem I'm facing and I was not able to solve by myself.
The problems (or SwiftUI bugs?) are the following:
a) I cannot select a value in a Picker two times
b) Strange behaviour when I try to hide some fields in my Form
The way to replicate this problems with the code attached is the following:
Run the application
Go to the tab Create
Click on Firewall Policy to create a new one
Click on picker Protocol and change the value (e.g. UDP)
Try to change the value again (e.g. TCP). Then, problem a) appears. Picker shows as "selected" but it doesn't work
Go to the picker Action and change value to Deny, then some rows in the form are hidden (expected behaviour)
Now, try to change the picker Action again to Allow, then b) problem appears, I get a strange view change and a blank screen
I'm running this with Xcode 11.3 on MacOS 10.15.2. Any help or tip is welcome!
import SwiftUI
struct ContentView: View {
#State var selectedTab = 1
var body: some View {
TabView(selection: $selectedTab){
CreateView(selectedTab: $selectedTab)
.tabItem {
Image(systemName: "plus")
Text("Create")
}.tag(0)
ListView()
.tabItem {
Image(systemName: "cloud")
Text("List")
}.tag(1)
}
}
}
struct CreateView: View {
#Binding var selectedTab: Int
var body: some View {
VStack{
NavigationView{
List{
Text("Server")
NavigationLink(destination: CreateFirewallPolicyView(selectedTab: $selectedTab)){
Text("Firewall Policy")
}
}
.navigationBarTitle("Select the element you want to create", displayMode: .inline)
}
}
}
}
struct ListView: View {
var body: some View {
NavigationView{
List{
Section(header: Text("Servers")){
Text("Server 1")
Text("Server 2")
}
Section(header: Text("Firewall policies")){
Text("Firewall 1")
Text("Firewall 2")
}
}
.navigationBarTitle("My virtual datacenter", displayMode: .large)
}
}
}
struct CreateFirewallPolicyView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#Binding var selectedTab: Int
#State private var name: String = ""
#State private var allowed_ip: String = ""
#State private var ports: String = ""
#State private var description: String = ""
#State private var selectedAction = RuleAction.allow
#State private var selectedProtocol = NetworkProtocol.tcp
#State private var rules: [Rule] = []
var body: some View {
Form {
Section(header: Text("Name of the firewall policy")){
TextField("Nombre", text: $name)
}
Section(header: Text("New rule")){
Picker(selection: $selectedAction, label: Text("Action")) {
ForEach(RuleAction.allCases, id:\.self) { fw_action in
Text(fw_action.name)
}
}
if (selectedAction == RuleAction.allow){
TextField("Allowed IP", text: $allowed_ip)
Picker(selection: $selectedProtocol, label: Text("Protocol")) {
ForEach(NetworkProtocol.allCases, id:\.self) { fw_protocol in
Text(fw_protocol.name)
}
}
TextField("Ports", text: $ports)
}
TextField("Description", text: $description)
Button(action: {
if self.selectedAction == RuleAction.deny{
self.ports = ""
self.allowed_ip = ""
self.selectedProtocol = NetworkProtocol.any
}
self.rules.append(Rule(id: UUID().uuidString, protocol: self.selectedProtocol, port: (self.ports.isEmpty ? nil : self.ports), source: (self.allowed_ip.isEmpty ? "0.0.0.0" : self.allowed_ip), description: (self.description.isEmpty ? nil : self.description), action: self.selectedAction))
self.allowed_ip = ""
self.ports = ""
self.description = ""
self.selectedAction = RuleAction.allow
self.selectedProtocol = NetworkProtocol.tcp
}) {
HStack{
Spacer()
Text("Add new rule")
}.disabled(self.selectedAction == RuleAction.allow && (self.selectedProtocol == NetworkProtocol.tcp || self.selectedProtocol == NetworkProtocol.udp || self.selectedProtocol == NetworkProtocol.tcp_udp) && self.ports.isEmpty)
}
}
Section(header: Text("Rules to add")){
ForEach(self.rules, id:\.self) { rule in
Text("\(rule.action.rawValue.capitalized) - \(rule.source ?? "all") - \(rule.protocol.rawValue) - \(rule.port ?? "")")
}.onDelete(perform: delete)
}
}
.navigationBarTitle("Create Firewall Policy")
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
},
trailing:
Button(action: {
print("Create")
}) {
Text("Create")
}
.disabled(name.isEmpty || rules.count == 0)
)
}
func delete(at offsets: IndexSet) {
rules.remove(atOffsets: offsets)
}
}
struct Rule:Codable, Hashable, Identifiable{
let id: String
var `protocol`: NetworkProtocol
var port: String?
var portFrom: Int?
var portTo: Int?
var source: String?
var description: String?
var action: RuleAction
}
enum NetworkProtocol: String, Codable, Hashable, CaseIterable{
case tcp = "TCP"
case udp = "UDP"
case icmp = "ICMP"
case tcp_udp = "TCP/UDP"
case ipsec = "IPSEC"
case gre = "GRE"
case any = "ANY"
var name: String {
return "\(self.rawValue)"
}
}
enum RuleAction: String, Codable, Hashable, CaseIterable{
case allow
case deny
var name: String {
return "\(self)".capitalized
}
}

Related

Picker not selecting the desired option

I am trying to setup a picker, simple. I am successfully fetching an array of projects from firebase and populating the picker with the names of the projects. The problem that I am having is that I need to get the project id when I click the list but it's not doing anything after I click the option that I want. I tried to run it in a simulator and also on my iPhone and nothing happens after I make the selection. I am pretty sure I am not updating the picker and thus I am not updating the variable with the selected project id. I tried using the .onChange on the picker but nothing happens.
import SwiftUI
struct NewProjectView: View {
#ObservedObject var viewModel = ProjectViewModel()
#ObservedObject var clientViewModel = ClientFeedViewModel()
#Environment (\.dismiss) var dismiss
#State var projectName: String = "s"
var clientNameIsEmpty: Bool {
if projectName.count < 3 {
return true
} else {
return false
}
}
var clients: [Client] {
return clientViewModel.clients
}
#State var selectedClient: String = ""
var body: some View {
NavigationView {
VStack {
Picker("", selection: $selectedClient) {
ForEach(clients, id:\.self) {
Text($0.clientName)
//I need to exctract the project id so I can pass it on
}
}
.pickerStyle(.menu)
CustomTextField(text: $projectName, placeholder: Text("Client Name"), imageName: "person.text.rectangle")
.padding()
.background(Color("JUMP_COLOR")
.opacity(0.75)
)
.cornerRadius(10)
.padding(.horizontal, 40)
Text("Name must contain more than 3 characters")
.font(.system(.subheadline))
.foregroundColor(.gray.opacity(0.3))
.padding(.top, 30)
.toolbar {
ToolbarItem(placement: .navigationBarLeading, content: {
Button(action: {
dismiss()
}, label: {
Text("Cancel")
})
})
ToolbarItem(placement: .navigationBarTrailing , content: {
Button(action: {
viewModel.newProject(name: projectName)
dismiss()
}, label: {
Text("Save")
})
.disabled(clientNameIsEmpty)
})
}
}
}
.presentationDetents([.height(400)])
//.presentationDetents([.medium])
.presentationDragIndicator(.visible)
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView()
}
}
Here is the picker populated with the foo data: picker
Your selection variable $selectedClient needs to have a type that matches the tagged value of each item in the picker.
As you're not specifying an explicit .tag for your text, the ForEach creates an implicit one using what it's using for tracking its loop, which in this case looks like it's a Client.
You can either change selectedClient to be a type of Client, or tag your displayed subview with the string value to populate selectedClient with, e.g.:
ForEach(clients, id: \.self) { client in
Text(client.clientName)
.tag(client.clientID)
}
Also, if each client has a unique ID, you're better off using that as ForEach's identifier than \.self. You can either specify id: \.clientID, etc., to use a single attribute – or you can add Identifiable conformance to Client and make sure that it has an id value that is guaranteed to be unique.
import SwiftUI
import Firebase
struct NewProjectView: View {
#ObservedObject var viewModel = ProjectViewModel()
#ObservedObject var clientViewModel = ClientFeedViewModel()
#Environment (\.dismiss) var dismiss
#State var projectName: String = "s"
var clientNameIsEmpty: Bool {
if projectName.count < 3 {
return true
} else {
return false
}
}
var clients: [Client] {
return clientViewModel.clients
}
#State var selectedClient: Client = Client(id: "", clientName: "Blank", timestamp: Timestamp(), ownerId: "", ownerUsername: "")
var body: some View {
NavigationView {
VStack {
Picker("d", selection: $selectedClient) {
ForEach(clients, id:\.id) { client in
Text(client.clientName)
.tag(client)
//I need to exctract the project id so I can pass it on
}
}
.pickerStyle(.menu)
Text(selectedClient.id ?? "")
CustomTextField(text: $projectName, placeholder: Text("Client Name"), imageName: "person.text.rectangle")
.padding()
.background(Color("JUMP_COLOR")
.opacity(0.75)
)
.cornerRadius(10)
.padding(.horizontal, 40)
Text("Name must contain more than 3 characters")
.font(.system(.subheadline))
.foregroundColor(.gray.opacity(0.3))
.padding(.top, 30)
.toolbar {
ToolbarItem(placement: .navigationBarLeading, content: {
Button(action: {
dismiss()
}, label: {
Text("Cancel")
})
})
ToolbarItem(placement: .navigationBarTrailing , content: {
Button(action: {
viewModel.newProject(name: projectName)
dismiss()
}, label: {
Text("Save")
})
.disabled(clientNameIsEmpty)
})
}
}
}
.presentationDetents([.height(400)])
//.presentationDetents([.medium])
.presentationDragIndicator(.visible)
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView()
}
}

Can't transfer variable from one watchos view to another view, Using swiftui

I am trying to get data from one view to another.
I can not figure out how to get values from the fourth view array into the Third view.
I am not using storyboards. I tried using #EnvironmentObject but can not make it work. New to coding. In xcode I am using watchos without app.
I tried to strip out most of the code and leave just the important stuff that can be tested. I used NavigationLink(destination: )to transfer between views.
enter code here
class viewFromEveryWhere: ObservableObject {
#Published var testname2: String = "testTTname"
}
struct secondView: View {
var body: some View {
Text("second view")
List(1..<7) {
Text("\($0)")
}
}
}
struct thirdView: View {
#EnvironmentObject var testname2: viewFromEveryWhere
#EnvironmentObject var testSixTestArray: viewFromEveryWhere
#State var sixTestArray:[String] = ["ww","GS","DW","CD","TS","JW",]
var body: some View {
List(sixTestArray, id:\.self) {
Text($0)
}
}
}
struct fourthView: View {
#StateObject var testname2 = viewFromEveryWhere()
#State private var name: String = ""
#State var testSixTestArray:[String] = []
func collectName () {
print("collectName triggered")
if testSixTestArray.count < 5 {
// testSixTestArray.append(name)
print(name)
print(testSixTestArray)
}
// .enviromentObject(testSixTestArray)
}
var body: some View {
VStack(alignment: . leading) {
Text("Type a name")
TextField("Enter your name", text: $name)
Text("Click to add, \(name)!")
// Button("click this if \(name) is correct") {}
Button(action:{
print("Button Tapped")
collectName()
print(testSixTestArray.count)
name = ""
}) {
Text("Add \(name) to list")
}
// .buttonStyle(GrowingButton1())
}
Text("forth view")
// testSixTestArray.append(name)
.environmentObject(testname2)
}
}
/*func presentTextInputControllerWithSuggestions(forLanguage suggestionsHandler:
((String)-> [Any]?)?,
allowedInputMode inputMode:
WKTextInputMode,
completion: #escaping ([Any]?) -> Void) {}
*/
struct ContentView: View {
#State var sixNameArray:[String] = ["","","","","","",]
#State var messageTextBox: String = "Start"
#State var button1: String = "Button 1"
#State var button2: String = "Button 2"
#State var button3: String = "Button 3"
var body: some View {
NavigationView {
VStack{
Text(messageTextBox)
.frame(width: 120, height: 15, alignment: .center)
.truncationMode(.tail)
.padding()
NavigationLink(destination: secondView(),
label:{
Text(button1)
})
.navigationBarTitle("Main Page")
NavigationLink(destination: thirdView(),
label:{
Text(button2)
})
NavigationLink(destination: fourthView(),
label:{
Text(button3)
})
}
}
}
}
enter code here

TabView is not switching tabs properly in SwiftUI

I'm having a weird problem that I can't seem to figure out with SwiftUI. I have a TabView in my ContentView, there are 3 tabs (chat list, user list, and profile) the app loads up on the chat list tab. The problem is, when I select the second tab (user list) it goes to that tab for a split second, then goes right back to the chat list. It doesn't make any sense to me. The 2 main tabs make an API call to get information from a server, and everything is working great, except that first click.
The app loads up, I click the user list tab and it shows for a split second, then goes back to the chat list tab. I can then click the user list tab again and it will go to that tab and stay there, but the first click on that tab always sends you back to the chat list tab.
I'll post up some of my code, hopefully someone will be able to see what I'm doing wrong, because I sure can't.
ContentView
struct ContentView: View {
#Environment(\.managedObjectContext) private var viewContext
#State var selectedTab = 0
#State var setup: Bool = false
#State var notificationChatID: String = ""
#ObservedObject var userModel: UserModel = UserModel()
#ObservedObject var chatModel: ChatModel = ChatModel()
#ObservedObject var appState: AppState = AppState.shared
var pushNavigationBinding : Binding<Bool> {
.init { () -> Bool in
appState.selectedChatID != nil
}
set: { (newValue) in
if !newValue {
appState.selectedChatID = nil
}
}
}
let settings = UserDefaults.standard
var body: some View {
ZStack {
if setup {
TabView(selection: $selectedTab) {
ChatList(launchedChatID: appState.selectedChatID ?? "", userModel: userModel, chatModel: chatModel)
.tabItem {
Image(systemName: "message.circle.fill")
Text("Active Chats")
}
UserList(userModel: userModel)
.tabItem {
Image(systemName: "person.3.fill")
Text("User List")
}
ProfileView()
.tabItem {
Image(systemName: "person.crop.circle")
Text("Profile")
}
}
} else {
Onboarding(userModel: userModel, isSetup: $setup)
}
}
.onReceive(NotificationCenter.default.publisher(for: Notification.Name.NewMessage), perform: { notification in
if let info = notification.userInfo {
let chatID = info["chatID"] as? String ?? ""
if chatID != "" {
chatModel.selectedChat = chatID
appState.selectedChatID = chatID
self.notificationChatID = chatID
}
}
})
}
Then my UserList
struct UserList: View {
#ObservedObject var userModel: UserModel
#ObservedObject var chatModel: ChatModel = ChatModel()
#State var action: Int? = -1
var body: some View {
NavigationView {
VStack {
List {
ForEach(0..<userModel.arrayOfUsers.count, id: \.self) { index in
ZStack(alignment: .leading) {
NavigationLink(
destination: ChatView(model: chatModel, userModel: userModel, item: $action),
tag: index,
selection: $action
) {
EmptyView().frame(width: .zero, height: .zero, alignment: .center)
}
Button(action: {
print("You selected \(userModel.arrayOfUsers[index].name)")
userModel.selectedUserName = userModel.arrayOfUsers[index].name
userModel.selectedUserID = userModel.arrayOfUsers[index].id
self.action = index
}) {
Text(userModel.arrayOfUsers[index].name)
}
}
}
}
Spacer()
}.navigationBarTitle(Text("Users"), displayMode: .inline)
}.onAppear() {
print("Inside the userlist on appear")
if userModel.arrayOfUsers.count == 0 {
ApiService.getUsers() { (res) in
switch(res) {
case .success(let response):
print("In success")
let users = response!.users!
DispatchQueue.main.async {
for user in users.users {
userModel.arrayOfUsers.append(user)
}
}
break
case .failure(let error):
print("Error getting users")
print(error)
break
}
}
}
}
}
}
My userModel.arrayOfUsers is #Published
UserModel
class UserModel: ObservableObject {
var name: String = ""
var id: String = ""
var myUserID: String = ""
#Published var arrayOfUsers: [User] = []
var selectedUserID: String = ""
var selectedUserName: String = ""
}
In the console in Xcode I see
Inside the userlist on appear
...(network stuff)
In the success
In the on appear in ChatList
So it's loading the UserList, it shows the network call out to my API, it shows the In the success from the API call in the UserList, then the very next thing is back to the In the on appear in ChatList I can't figure out why it's kicking me back to the chat list.
You're binding your TabView's current tab to $selectedTab, but not providing SwiftUI with any information on how to alter that value when the user changes tabs. And so, because selectedTab hasn't changed, when the drawing system comes to review your view structure, it still concludes that you want to see the first tab.
You should add a .tag modifier after each .tabItem to tell SwiftUI what values represent each tab. Then, when the user selects each tab, selectedTab will be updated and the tab choice will "stick".
For example:
TabView(selection: $selectedTab) {
ChatList(launchedChatID: appState.selectedChatID ?? "", userModel: userModel, chatModel: chatModel)
.tabItem {
Image(systemName: "message.circle.fill")
Text("Active Chats")
}
.tag(0)
UserList(userModel: userModel)
.tabItem {
Image(systemName: "person.3.fill")
Text("User List")
}
.tag(1)
ProfileView()
.tabItem {
Image(systemName: "person.crop.circle")
Text("Profile")
}
.tag(2)
}
Note that unless you're persisting the user's choice in some way (e.g., by declaring your state variable with #SceneStorage) you can get the same effect by not using a selection argument at all.

SwiftUI: Picker doesn't update text in same view

I have this simple situation:
struct User: Hashable, Identifiable {
var id: Int
var name: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
let bob = User(id: 1, name: "Bob")
let john = User(id: 2, name: "John")
let users = [bob, john]
struct ParentView: View {
#State private var user: User?
var body: some View {
VStack(spacing: 0) {
// Other elements in view...
Divider()
ChildPickerView(user: $user)
Spacer()
}
}
}
struct ChildPickerView: View {
#Binding var user: User?
var body: some View {
HStack {
Text("Selected : \(author?.name ?? "--")")
Picker(selection: $user, label: Text("Select a user")) {
ForEach(0..<users.count) {
Text(users[$0].name)
}
}
}
.padding()
}
}
When I select another value in the picker, the name in the Text() above isn't updated.
However, when tapping the picker again, there is a tick near the selected user, which means the value has actually been selected. Why is the text not updated then?
Thank you for your help
Type of selection and picker content id or tag should be the same. Find below fixed variant.
Tested with Xcode 12.1 / iOS 14.1.
VStack {
Text("Selected : \(user?.name ?? "--")")
Picker(selection: $user, label: Text("Select a user")) {
ForEach(users) {
Text($0.name).tag(Optional($0))
}
}
}

SwiftUI: how to get rid of Segmented Control text movement when an alert is shown?

In a small sample SwiftUI app, I have a settings view that shows a couple of option selections, implemented as segmented controls. The text in these segmented controls visibly moves when an alert is presented or dismissed. Is there a way to get rid of this glitch?
Paste this in a Playground to reproduce:
import SwiftUI
import PlaygroundSupport
struct FlickeringSegmentsView: View {
#State var option = 0
#State var alerting = false
var body: some View {
VStack(alignment: .center, spacing: 120) {
Picker("options", selection: $option) {
Text("Option A").tag(0)
Text("Option B").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding(16)
Button(action: { self.alerting.toggle() },
label: { Text("Show Alert") }
)
.alert(isPresented: $alerting) {
Alert(title: Text("Alert"))
}
}
}
}
PlaygroundPage.current.setLiveView(FlickeringSegmentsView())
This issue is resolved in Xcode 12 beta using the included iOS 14 simulator (and hopefully stays that way).
I hope code below should help you:
public protocol SegmentedPickerViewElementTraits: Hashable {
var localizedText: String { get }
}
public struct SegmentedPickerView<Value, Data, ID, Label>: View
where
Value: SegmentedPickerViewElementTraits,
Data: RandomAccessCollection,
Data.Element == Value,
ID: Hashable,
Label: View {
public let data: Data
public let id: KeyPath<Data.Element, ID>
public let selection: Binding<Value>
public let label: Label
public init(data: Data,
id: KeyPath<Data.Element, ID>,
selection: Binding<Value>,
label: Label) {
self.data = data
self.id = id
self.selection = selection
self.label = label
}
public var body: some View {
Picker(selection: selection, label: label) {
ForEach(data, id: id) {
Text($0.localizedText).tag($0)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
and lets modify your code:
enum Options: UInt8, CaseIterable {
case optionA
case optionB
}
extension Options: SegmentedPickerViewElementTraits {
var localizedText: String {
switch self {
case .optionA:
return "Option A"
case .optionB:
return "Option B"
}
}
}
struct FlickeringSegmentsView: View {
#State
var option: Options = .optionA
#State
var alerting = false
var body: some View {
VStack(alignment: .center, spacing: 120) {
SegmentedPickerView(
data: Options.allCases,
id: \.self,
selection: $option,
label: Text("options")
)
.padding(16)
Button(
action: { self.alerting.toggle() },
label: { Text("Show Alert") }
)
.alert(isPresented: $alerting) {
Alert(title: Text("Alert"))
}
}
}
}