why my logout button can logout but can't switch the view - swift

I have already set a logout button. The function of that button is correct which can actually logout. But there is a problem: when I press the logout button, I can not switch the page to the view I want, which is LoginsignupView. I can't find amything wrong in my code.
I want to know how to make it correctly.
Here is the code about logout
import SwiftUI
struct MainView: View {
#State private var selection = 0
#ObservedObject private var httpClient = HTTPUser()
#State var isin : Bool = true
var body: some View {
if #available(iOS 14.0, *) {
ZStack{
TabView(selection: $selection){
profile1View()
.tag(0)
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
//List(self.httpClient.user,id: \.id){ user in
profile3()
.tag(1)
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
ZStack{
Image("background")
.resizable()
.scaledToFill()
.frame(minWidth: 0, maxWidth: .infinity)
.edgesIgnoringSafeArea(.all)
NavigationLink(
destination: LoginsignupView().navigationBarBackButtonHidden(true)
.navigationBarHidden(true))
{
Text("logout").foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical)
.frame(width: UIScreen.main.bounds.width - 100)
.background(
LinearGradient(gradient: .init(colors: [Color("Color"),Color("Color1"),Color("Color2")]), startPoint: .leading, endPoint: .trailing)
)
}
}
.tag(2)
.onAppear(perform: httpClient.Logout)
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
.zIndex(0)
.onAppear{
UITabBar.appearance().barTintColor = .white
}
}
}
if #available(iOS 14.0, *) {
TabBarView(selection: $selection)
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
} else {
// Fallback on earlier versions
}
Divider()
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}

If the intent is to push a LoginSignupView once "Logout" is pressed, then you need a NavigationView somewhere in the view hierarchy. NavigationLink itself won't do much.
However, from your code it looks like you perform logout once the last tab is shown. In which case you might also want to bind your existing NavigationLink to a boolean property. For example your tab might look like this:
NavigationView {
.....
ZStack{
Image("background")
.resizable()
.scaledToFill()
.frame(minWidth: 0, maxWidth: .infinity)
.edgesIgnoringSafeArea(.all)
NavigationLink(
destination: LoginsignupView().navigationBarBackButtonHidden(true)
.navigationBarHidden(true), isActive:$showingLogout)
{
Text("logout").foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical)
.frame(width: UIScreen.main.bounds.width - 100)
.background(
LinearGradient(gradient: .init(colors: [Color("Color"),Color("Color1"),Color("Color2")]), startPoint: .leading, endPoint: .trailing)
)
}
}
.tag(2)
.onAppear(perform: {
httpClient.Logout()
showingLogout = true
})
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}

Related

SwiftUI button glitches on keyboard dismiss

I have a button on my view that, when pressed, calls a hideKeyboard function which is the following:
func hideKeyboard() {
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
}
However, when the button is pressed and the keyboard gets dismissed, a glitch occurs where the button stays in place while the view moves downward:
https://giphy.com/gifs/Z7qCDpRSGoOb9CbVRQ
Reproducible example:
import SwiftUI
struct TestView: View {
#State private var username: String = ""
#State private var password: String = ""
#State private var isAnimating: Bool = false
var lightGrey = Color(red: 239.0/255.0,
green: 243.0/255.0,
blue: 244.0/255.0)
var body: some View {
ZStack() {
VStack() {
Spacer()
Text("Text")
.font(.title)
.fontWeight(.semibold)
.padding(.bottom, 15)
.frame(maxWidth: .infinity, alignment: .leading)
Text("Text")
.font(.subheadline)
.padding(.bottom)
.frame(maxWidth: .infinity, alignment: .leading)
TextField("username", text: $username)
.padding()
.background(self.lightGrey)
.cornerRadius(5.0)
.padding(.bottom, 20)
SecureField("password", text: $password)
.padding()
.background(self.lightGrey)
.cornerRadius(5.0)
.padding(.bottom, 20)
Button(action: {
self.hideKeyboard()
login()
})
{
if isAnimating {
ProgressView()
.colorScheme(.dark)
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
else {
Text("Text")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
}
.disabled(username.isEmpty || password.isEmpty || isAnimating)
Text("Text")
.font(.footnote)
.frame(maxWidth: .infinity, alignment:.leading)
Spacer()
}
.padding()
.padding(.bottom, 150)
.background(Color.white)
}
}
func hideKeyboard() {
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
}
func login() {
isAnimating = true
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
This is due to view replacement inside button, find below a fixed re-layout.
Tested with Xcode 13.2 / iOS 15.2 (slow animation was activated for demo)
Button(action: {
self.hideKeyboard()
login()
})
{
VStack { // << persistent container !!
if isAnimating {
ProgressView()
.colorScheme(.dark)
}
else {
Text("Text")
}
}
.foregroundColor(.white)
.font(.headline)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
.disabled(username.isEmpty || password.isEmpty || isAnimating)
Looks like a conflict between UIApplication.shared.sendAction and SwiftUI: hiding the keyboard starts the animation, but updating the isAnimating property resets it.
Changing the order of calls solves the problem:
Button(action: {
login()
self.hideKeyboard()
})

Using TextField hides the ScrollView beneath it in VStack

This view hold a list of pdf names which when tapped open webviews of pdf links.
The view has a search bar above the list which when tapped causes the scrollview to disappear.
struct AllPdfListView: View {
#Environment(\.presentationMode) var mode: Binding<PresentationMode>
#ObservedObject var pdfsFetcher = PDFsFetcher()
#State var searchString = ""
#State var backButtonHidden: Bool = false
#State private var width: CGFloat?
var body: some View {
GeometryReader { geo in
VStack(alignment: .leading, spacing: 1) {
HStack(alignment: .center) {
Image(systemName: "chevron.left")
Text("All PDFs")
.font(.largeTitle)
Spacer()
}
.padding(.leading)
.frame(width: geo.size.width, height: geo.size.height / 10, alignment: .leading)
.background(Color(uiColor: UIColor.systemGray4))
.onTapGesture {
self.mode.wrappedValue.dismiss()
}
HStack(alignment: .center) {
Image(systemName: "magnifyingglass")
.padding([.leading, .top, .bottom])
TextField ("Search All Documents", text: $searchString)
.textFieldStyle(PlainTextFieldStyle())
.autocapitalization(.none)
Image(systemName: "slider.horizontal.3")
.padding(.trailing)
}
.overlay(RoundedRectangle(cornerRadius: 10).stroke(.black, lineWidth: 1))
.padding([.leading, .top, .bottom])
.frame(width: geo.size.width / 1.05 )
ScrollView {
ForEach($searchString.wrappedValue == "" ? pdfsFetcher.pdfs :
pdfsFetcher.pdfs.filter({ pdf in
pdf.internalName.contains($searchString.wrappedValue.lowercased())
})
, id: \._id) { pdf in
if let parsedString = pdf.file?.split(separator: "-") {
let request = URLRequest(url: URL(string: "https://mylink/\(parsedString[1]).pdf")!)
NavigationLink(destination: WebView(request: request)
.navigationBarBackButtonHidden(backButtonHidden)
.navigationBarHidden(backButtonHidden)
.onTapGesture(perform: {
backButtonHidden.toggle()
})) {
HStack(alignment: .center) {
Image(systemName: "doc")
.padding()
.frame(width: width, alignment: .leading)
.lineLimit(1)
.alignmentGuide(.leading, computeValue: { dimension in
self.width = max(self.width ?? 0, dimension.width)
return dimension[.leading]
})
Text(pdf.internalName)
.padding()
.multilineTextAlignment(.leading)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
}
.padding(.leading)
}
}
}
.navigationBarHidden(true)
}
.accentColor(Color.black)
.onAppear{
pdfsFetcher.pdfs == [] ? pdfsFetcher.fetchPDFs() : nil
}
}
}
}
}
Pdf list and Searchbar.
The same view on Searchbar focus.
I would like the search string to filter the list of pdfs while maintaining the visibility of the list.
I was able to fix this by making my #ObservableObject an #EnvironmentObject in my App :
#main
struct MyApp: App {
#ObservedObject var pdfsFetcher = PDFsFetcher()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(pdfsFetcher)
}
}
}
struct AllPdfListView: View {
#EnvironmentObject var pdfsFetcher: PDFsFetcher
}

Adding a "Hamburger" Menu to IOS application

I am trying to create a hamburger menu that when you click the "hamburger" (three horizontal lines) button, the menu will slide out. I am following the tutorial found here, but the only thing that isn't working is the lines for the Hamburger image is not showing up on my application. Everything else works, but for some reason this is the one thing that is not working.
Here is my code for the ContentView, where it hosts the problem code
struct ContentView: View {
#State var showMenu = false
var body: some View {
let drag = DragGesture()
.onEnded {
if $0.translation.width < -100 {
withAnimation {
self.showMenu = false
}
}
}
return NavigationView {
GeometryReader { geometry in
ZStack(alignment: .leading) {
MainView(showMenu: self.$showMenu)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(x: self.showMenu ? geometry.size.width/2 : 0)
.disabled(self.showMenu ? true : false)
if self.showMenu {
MenuView()
.frame(width: geometry.size.width/2)
.transition(.move(edge: .leading))
}
}
.gesture(drag)
}
.navigationBarTitle("Side Menu", displayMode: .inline) // this works
//somewhere below here is the problem
.navigationBarItems(leading: (
Button(action: {
withAnimation {
self.showMenu.toggle()
}
}) {
Image(systemName: "three_horizontal_lines")
.imageScale(.large)
}
))
}
}
}
Here is the MainView:
struct MainView: View{
#Binding var showMenu: Bool
var body: some View{
Button(action: {
withAnimation{
self.showMenu = true
}
}){
Text("Show Menu")
}
}
}
Lastly, this is the MenuView:
struct MenuView: View{
var body: some View{
VStack(alignment: .leading){
HStack{
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Profile")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 100)
HStack{
Image(systemName: "envelope")
.foregroundColor(.gray)
.imageScale(.large)
Text("Messages")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 30)
HStack{
Image(systemName: "gear")
.foregroundColor(.gray)
.imageScale(.large)
Text("Settings")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 30)
Spacer()
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color(red: 32/255, green: 32/255, blue: 32/255))
.edgesIgnoringSafeArea(/*#START_MENU_TOKEN#*/.all/*#END_MENU_TOKEN#*/)
}
}
I have checked for any misspellings and even copied and pasted the code from the original tutorial, but it seems nothing allows me to see the burger image like is shown on the tutorial. Any thoughts on what else I could try?

Collapse sidebar in SwiftUI (Xcode 12)

I'm trying to do a simple application in SwiftUI taking advantage of SwiftUI 2.0's new multiplatform project template, and I wish to add the option to collapse the sidebar as many other apps do.
I tried adding a boolean state variable that controls whether the sidebar should show or not, but that doesn't work because then the main view is turned translucent (I guess this is because macOS thinks the sidebar is now the main view).
Is there a way to natively achieve this in SwiftUI?
Please note I'm using macOS Big Sur, Xcode 12, and SwiftUI 2.0
Thanks in advance.
My code
ContentView.swift
import SwiftUI
struct ContentView: View {
#if os(iOS)
#Environment(\.horizontalSizeClass) private var horizontalSizeClass
#endif
#ViewBuilder var body: some View {
#if os(iOS)
if horizontalSizeClass == .compact {
TabController()
} else {
SidebarNavigation()
}
#else
SidebarNavigation()
.frame(minWidth: 900, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity)
#endif
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.sizeThatFits)
}
}
Sidebar.swift
import SwiftUI
struct SidebarNavigation: View {
enum HyperspaceViews {
case home
case localTimeline
case publicTimeline
case messages
case announcements
case community
case recommended
case profile
}
#State var selection: Set<HyperspaceViews> = [.home]
#State var searchText: String = ""
#State var showComposeTootView: Bool = false
#State var showNotifications: Bool = false
#State private var showCancelButton: Bool = false
var sidebar: some View {
VStack {
HStack {
TextField("Search...", text: $searchText)
.cornerRadius(4)
}
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
List(selection: self.$selection) {
Group {
NavigationLink(destination: Timeline().container.frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Home", systemImage: "house")
}
.accessibility(label: Text("Home"))
.tag(HyperspaceViews.home)
NavigationLink(destination: Text("Local").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Local", systemImage: "person.2")
}
.accessibility(label: Text("Local"))
.tag(HyperspaceViews.localTimeline)
NavigationLink(destination: Text("Public").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Public", systemImage: "globe")
}
.accessibility(label: Text("Public"))
.tag(HyperspaceViews.localTimeline)
NavigationLink(destination: Text("Messages").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Messages", systemImage: "bubble.right")
}
.accessibility(label: Text("Message"))
.tag(HyperspaceViews.localTimeline)
Divider()
NavigationLink(destination: Text("Announcements").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Announcements", systemImage: "megaphone")
}
.accessibility(label: Text("Announcements"))
.tag(HyperspaceViews.announcements)
NavigationLink(destination: Text("Community").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Community", systemImage: "flame")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.community)
NavigationLink(destination: Text("Recommended").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Recommended", systemImage: "star")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.recommended)
Divider()
NavigationLink(destination: Text("Recommended").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("hyperspacedev", systemImage: "tag")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.recommended)
}
}
.overlay(self.profileButton, alignment: .bottom)
.listStyle(SidebarListStyle())
}
}
var profileButton: some View {
VStack(alignment: .leading, spacing: 0) {
Divider()
NavigationLink(destination: ProfileView().container.frame(maxWidth: .infinity, maxHeight: .infinity)) {
HStack {
Image("amodrono")
.resizable()
.clipShape(Circle())
.frame(width: 25, height: 25)
Text("amodrono")
.font(.headline)
}
.contentShape(Rectangle())
}
.accessibility(label: Text("Your profile"))
.padding(.vertical, 8)
.padding(.horizontal, 16)
.buttonStyle(PlainButtonStyle())
}
.tag(HyperspaceViews.profile)
}
var body: some View {
NavigationView {
#if os(macOS)
sidebar.frame(minWidth: 100, idealWidth: 180, maxWidth: 200, maxHeight: .infinity)
#else
sidebar
#endif
Text("Content List")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.sheet(isPresented: self.$showComposeTootView) {
ComposeTootView(showComposeTootView: self.$showComposeTootView)
.frame(minWidth: 400, maxWidth: .infinity, minHeight: 200, maxHeight: .infinity)
}
.toolbar {
ToolbarItem {
Button(action: {
self.showNotifications.toggle()
}) {
Image(systemName: "bell")
}
.popover(
isPresented: self.$showNotifications,
arrowEdge: .bottom
) {
LazyVStack {
ForEach(0 ..< 10 ) { i in
Label("#\(i) liked your post!", systemImage: "hand.thumbsup")
.padding()
Divider()
}
}
}
}
ToolbarItem {
Button(action: {
self.showComposeTootView.toggle()
}) {
Image(systemName: "square.and.pencil")
}
}
}
}
}
struct SidebarNavigation_Previews: PreviewProvider {
static var previews: some View {
SidebarNavigation()
}
}
This worked for me -
https://developer.apple.com/forums/thread/651807
struct SwiftUIView: View {
var body: some View {
NavigationView{
}.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: toggleSidebar, label: {
Image(systemName: "sidebar.left")
})
}
}
}
}
func toggleSidebar() {
NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
It shows in the views on iOS so you will need some conditions for macOS only.
Apple provide NSToolbarToggleSidebarItemIdentifier which perform the toggleSidebar(_:) method.
.onAppear {
NSApp.keyWindow?.toolbar?.insertItem(withItemIdentifier: .toggleSidebar, at: 0)
}
This way will appear a button in your toolbar which action will invoke the sidebar toggle and it works perfectly.

How do you fill entire Button area with background View in WatchOS?

I am trying to have my background view span the entire area of a Button on an Apple Watch form factor.
struct SurveyView: View {
var body: some View {
Button(action: {
print("Test tapped.")
}) {
HStack {
Text("Test")
.fontWeight(.semibold)
}
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.foregroundColor(.white)
.background(LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .leading, endPoint: .trailing))
}
}
}
How can I make the background span the entire Button?
Update: Turns out my issue is also related to being in a List View. Setting a mask doesn't quite solve it.
struct SurveyView: View {
var body: some View {
List() {
Button(action: {
print("Test tapped.")
}) {
Text("Test")
.fontWeight(.semibold)
}
.background(Color.orange)
.mask(RoundedRectangle(cornerRadius: 24))
}
}
}
I would do this in the following way:
Button(action: {
print("Test tapped.")
}) {
Text("Test")
.fontWeight(.semibold)
.padding()
.foregroundColor(.white)
}
.background(LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .leading, endPoint: .trailing))
.mask(RoundedRectangle(cornerRadius: 24))
Update: the case for list
var body: some View {
List() {
Button(action: {
print("Test tapped.")
}) {
Text("Test")
.fontWeight(.semibold)
.padding()
}
.background(Color.orange)
.mask(RoundedRectangle(cornerRadius: 24))
.listRowPlatterColor(Color.clear)
}
}