SwiftUI ZStack first element is not displayed - ios

I'm new to SwiftUI, and I have a simple app with a ZStack:
struct ContentView: View {
#State var num : Int = 1
var body: some View {
NavigationView{
ZStack{
Text("asd")
.foregroundColor(.blue)
.frame(width: 400, height: 400, alignment: .center)
.background(.blue)
VStack{
List{
ListItem()
ListItem()
}
}
.toolbar{
Button{
num+=1
} label: {
Label("Add", systemImage: "plus")
}
}
}
}
}
}
The problem is that the blue frame with the text is not displayed:
Why is this happening?

You are using ZStack to wrap up everything.
Solution: Change from ZStack to VStack.
NavigationView{
VStack{ //this part

It is because the Text View is underneath the List in the ZStack.
If you move the Text to after the list, it will be shown on top.
ZStack {
VStack{
List {
ListItem()
ListItem()
}
.listStyle(.insetGrouped)
}
.toolbar{
Button{
num+=1
} label: {
Label("Add", systemImage: "plus")
}
}
Text("asd")
.foregroundColor(.blue)
.frame(width: 400, height: 400, alignment: .center)
.background(.blue)
}

Related

Swift ui stacks causing gap at the top of the screen when frame should be first

In Swift ui I have a tabview and am going to my profile test page but in the simulator it displaying in the middle of the page.
var body: some View {
VStack() {
Text("Welcome")
.font(.largeTitle)
.foregroundColor(.black)
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(.red)
VStack {
Image("murry")
.clipShape(Circle())
.shadow(radius: 10)
.overlay(Circle()
.stroke(Color.red, lineWidth: 5))
Text("Murry GoldBerg")
HStack{
Text("Following:0").foregroundColor(.white)
Text("Followers:2").foregroundColor(.white)
Text("Kids:0").foregroundColor(.white)
}
}
.padding(20)
.multilineTextAlignment(.center)
}
.frame(width: 450, height: 250)
}
Spacer()
}
}
My Code as to how am inserting my views in the tab view not showing it all as no need just a snippet
struct ContentView: View {
var body: some View {
TabView{
HomeView() .tabItem {
Image(systemName: "house")
Text("Home")
}
ProfileView()
.tabItem {
Image(systemName: "person.circle.fill")
Text("Profile")
}
StatsView()
.tabItem {
Image(systemName: "plus").renderingMode(.original).padding()
Text("Plus")
}
}
Even on a real device it is doing the same so I no its not just the simlutor.
The reason is there is only one VStack so it will be default the main layout of the view. Default VStack if has only one view is from center view.
You just need add another VStack to cover your VStack then it will layout from top
var body: some View {
VStack {
VStack() {
Text("Welcome")
.font(.largeTitle)
.foregroundColor(.black)
ZStack {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.fill(.red)
VStack {
Image("murry")
.clipShape(Circle())
.shadow(radius: 10)
.overlay(Circle()
.stroke(Color.red, lineWidth: 5))
Text("Murry GoldBerg")
HStack{
Text("Following:0").foregroundColor(.white)
Text("Followers:2").foregroundColor(.white)
Text("Kids:0").foregroundColor(.white)
}
}
.padding(20)
.multilineTextAlignment(.center)
}
.frame(width: 450, height: 250)
Spacer()
}
}
}

SwiftUI: Why does an EnvironmentalObject get reinitialized when you interact with a TextField in this navigation flow?

In my app you go through the onboarding during sign-up. That works perfectly. However, you can go through it again via the Profile Page.
The profile page code in question looks like this (embedded in a top-level NavigationView of course)
NavigationLink(destination:
EndDateView().environmentObject(OnboardingVM(coordinator: viewModel.appCoordinator))
) {
HStack {
Image(systemName: "chart.pie.fill")
.font(.title)
Text("Edit Spending Plan")
.fontWeight(.bold)
.scaledFont("Avenir", 20)
}
}
.buttonStyle(ButtonWithIcon())
This leads you to a screen where you set a Date via a date picker. All is good at this point.
When you navigate to the third page of this flow (Profile -> Datepicker -> Set Income) and interact with a SwiftUI TextField, the #EnvironmentObject reinitializes itself.
Below you will see the code snippets that show how we navigate/pass the env object around
DatePicker Navigation Code
NavigationLink(destination: SetIncomeView().environmentObject(onboardingVM)) {
PurpleNavigationButton(buttonText: onboardingVM.continueButton)
}
SetIncome Code
struct SetIncomeView: View {
#EnvironmentObject var onboardingVM: OnboardingVM
#ObservedObject var setIncomeVM = SetIncomeVM()
var body: some View {
VStack {
HStack {
CustomHeader1(text: SetIncomeContent.title)
Button(action: {
setIncomeVM.info.toggle()
}) {
Image(systemName: "info.circle")
}
}
.alert(isPresented: $setIncomeVM.info) {
Alert(title: Text(SetIncomeContent.title),
message: Text(SetIncomeContent.header),
dismissButton: .default(Text(SetIncomeContent.dismiss)))
}.padding()
Spacer()
ScrollView {
HStack {
CustomHeader2(text: SetIncomeContent.income)
TextField("", text: $onboardingVM.expectedIncomeAmount)
.keyboardType(.numberPad)
.frame(width: 100, height: 35, alignment: .center)
.scaledFont("Avenir", 20)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
HStack {
CustomHeader2(text: SetIncomeContent.onBasis)
Picker(selection: $onboardingVM.selectedBasis, label: Text("")) {
ForEach(0 ..< self.onboardingVM.basis.count) {
Text(self.onboardingVM.basis[$0])
}
}
.frame(width: 100)
.clipped()
CustomHeader2(text: SetIncomeContent.basis)
}
Button(action: {
setIncomeVM.otherIncome.toggle()
}) {
if setIncomeVM.otherIncome {
Image(systemName: "minus.circle")
} else {
Image(systemName: "plus.circle")
}
Text(SetIncomeContent.anotherSource)
.foregroundColor(.black)
.underline()
.fixedSize(horizontal: false, vertical: true)
.padding()
}
//TODO: I am getting a bug where if i type or scroll it closes the view below
HStack {
CustomHeader2(text: SetIncomeContent.income)
TextField("", text: $onboardingVM.additionalIncome)
.keyboardType(.numberPad)
.frame(width: 100, height: 35, alignment: .center)
.scaledFont("Avenir", 20)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.isHidden(!setIncomeVM.otherIncome)
HStack {
CustomHeader2(text: SetIncomeContent.onBasis)
Picker(selection: $onboardingVM.additionalBasis, label: Text("")) {
ForEach(0 ..< self.onboardingVM.basis.count) {
Text(self.onboardingVM.basis[$0])
}
}
.frame(width: 100)
.clipped()
CustomHeader2(text: SetIncomeContent.basis)
}.isHidden(!setIncomeVM.otherIncome)
}
Spacer()
NavigationLink(destination: SetSavingsView().environmentObject(onboardingVM),
isActive: $setIncomeVM.savingsLink1Active) {
Button(action: {
setIncomeVM.savingsLink1Active.toggle()
}) {
Text(SetIncomeContent.noIncome)
.foregroundColor(.black)
.underline()
.fixedSize(horizontal: false, vertical: true)
.padding()
}
}
NavigationLink(destination: SetSavingsView().environmentObject(onboardingVM), isActive: $setIncomeVM.savingsLink2Active) {
Button(action: {
self.onboardingVM.saveIncomeBasis()
if !setIncomeVM.savingsLink2Active {
setIncomeVM.savingsLink2Active.toggle()
}
}) {
PurpleNavigationButton(buttonText: onboardingVM.continueButton)
}
}
}
Spacer()
}
}
Any idea why this happens?

Editing NavigationBarItems and NavigationBarTitle in SwiftUI inside TabView

I'm trying to change the navigation bar title and leading & trailing items in a SwiftUI app.
Here is the situation:
A user logs in, then he gets transferred to a view inside a TabView.
Before login, in the welcome screen and login & register screens I have no navigation bar title, but after login, I want to add the navigation bar items and title.
What is important to know is that my after-login-view is inside a TabView.
If I wrap my after-login-view in a new NavigationView and then change the navigation bar items and title it works! but it shows me 2 navigation bars:
which is not what I want.
here is the code I use :
This is the after-Login-View
import SwiftUI
struct DiscoveryView: View {
var body: some View {
List{
Text("List Items")
}.offset(y: 10)
.navigationBarTitle("", displayMode: .inline)
.navigationBarItems(leading:
Text("Discovery").font(Font.custom("Quicksand- Bold", size: 24))
, trailing:
Button(action: {
}) {
HStack{
Text("120").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color("BlueColor"))
Text("following").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color.black)
}
}
).navigationBarBackButtonHidden(true)
}
}
This is the TabView:
struct TabController : View {
#State private var selection = 0
var body: some View {
TabView(selection: $selection){
DiscoveryView()
.tabItem {
VStack {
Image(systemName: "list.dash")
Text("Discover")
}
}.tag(1)
ExploreView()
.tabItem {
VStack {
Image(systemName: "square.and.pencil")
Text("Explore")
}
}.tag(2)
SelfProfileView()
.tabItem{
VStack {
Image(systemName: "person.circle")
Text("Profile")
}
}.tag(3)
}.accentColor(Color("BlueColor"))
}
}
This is the code of the login page:
import SwiftUI
struct LoginView: View {
var body: some View {
ZStack{
VStack{
Image("mainLogo").resizable().frame(width: 250, height: 125)
Text("").frame(width: UIScreen.main.bounds.width, height: 100)
HStack{
TextField("Username / Email", text: $email)
.padding(.leading, 10)
.frame(width: 313, height: 49)
.background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")))
}
Text("").frame(width: UIScreen.main.bounds.width, height: 40)
HStack {
HStack{
if self.visable{
TextField("Password", text: $password)
.padding(.horizontal)
} else {
SecureField("Password", text: $password)
.padding(.horizontal)
}
Button(action: {
self.visable.toggle()
}){
Image(systemName: self.visable ? "eye.slash" : "eye")
.padding(.trailing, 20)
.foregroundColor(Color.black)
}
}.background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")) )
}.padding(.horizontal, 40).padding(.vertical)
Text("").frame(width: UIScreen.main.bounds.width, height: 100)
Button(action: {
//pass email password and conpassword to cognito
DSManager().signIn(username: self.email, password: self.password, error: {
error in
if let error = error{
self.error = error.errorString
self.alert.toggle()
print(error.errorString)
}
else{
DSManager().getSelfUserInformation(response: {
userInfo, userCollections,dsError in
if let dsError = dsError{
self.error = dsError.errorString
self.alert.toggle()
print(dsError.errorString)
}
if let userInfo = userInfo{
print("success")
//use userInfo to load stuff for profile page
if let userCollections = userCollections{
self.profileInfo.setProperties(userInfo: userInfo, collections: userCollections)
}
else{
self.profileInfo.setProperties(userInfo: userInfo, collections: [:])
}
self.isComplete.toggle()
}
})
}
})
}) {
Text("Login")
.fontWeight(.semibold)
.frame(width: 313, height: 48)
.background(fillAllFields() ? Color("YellowColor") : Color.gray)
.foregroundColor(Color.white)
.font(.system(size: 17))
.cornerRadius(15)
.shadow(color: Color("GrayColor"), radius: 0, x: 3, y: 3)
}.disabled(!fillAllFields())
NavigationLink(destination: ProfileView(), isActive: $isComplete) {
EmptyView()
}
Spacer()
}
.padding()
.navigationBarTitle("", displayMode: .inline)
if self.alert {
ErrorView(err: $error, alert: $alert)
}
}
}
func fillAllFields() -> Bool {
if self.email == "" || self.password == "" {
return false
}
return true
}
}
As mentioned, I'm trying to edit bar items and title of a view inside and tab view .
Thanks!
So as per your updated question, I added DiscoveryView Inside NavigationView and it worked as expected. I have added code and screenshot as well.
struct TabController : View {
#State private var selection = 0
var body: some View {
TabView(selection: $selection) {
NavigationView {
DiscoveryView()
}
.tabItem {
VStack {
Image(systemName: "list.dash")
Text("Discover")
}
}.tag(1)
Text("Explore View")
.tabItem {
VStack {
Image(systemName: "square.and.pencil")
Text("Explore")
}
}.tag(2)
Text("SelfProfileView")
.tabItem{
VStack {
Image(systemName: "person.circle")
Text("Profile")
}
}.tag(3)
}.accentColor(Color("BlueColor"))
}}

View with fullscreen image and navigationLink

i'm new to swiftui and struggling with some basic stuff
I'm trying to create a view with 2 buttons on the botton.
I want an image as background of the whole view.
var body: some View {
ZStack {
Image("bg-welcome").edgesIgnoringSafeArea(.all)
}
}
This works fine
I set my view like this
NavigationView {
ZStack {
VStack(alignment: HorizontalAlignment.leading, spacing: 10) {
Text("1").foregroundColor(.white)
Text("2").foregroundColor(.white)
Spacer()
Button(action: {}){
Text("ooooooooo")
}
}.background(Image("bg-welcome"))
}
}
Now I have 2 problems:
- a white space is dispalyed just before the background image
- the first text is pushed below, surely after the space reserved for the navigationbar and I don't want it because when I navigate to the next screen, the space is still taken and I want to have the whole avaiblable screen
thank you for your help
try this:
var body: some View {
NavigationView {
ZStack {
VStack(alignment: HorizontalAlignment.leading, spacing: 10) {
Text("1").foregroundColor(.white)
Text("2").foregroundColor(.white)
Spacer()
Button(action: {}){
Text("Button 1")
}
Button(action: {}){
Text("Button 2")
}
}.background(Image("remachine_poster")
.resizable()
.aspectRatio(contentMode: .fill)).edgesIgnoringSafeArea(.all)
}
}
}
you can add a padding to your button....
NavigationView {
ZStack {
VStack() {
Text("1").foregroundColor(.green).padding(.top, 40)
Text("2").foregroundColor(.green)
Spacer()
Button(action: {}){
Text("Button 1")
}.foregroundColor(Color.red)
Button(action: {}){
Text("Button 2")
}.foregroundColor(Color.red)
}
}.background(Image("remachine_poster")
.resizable()
.aspectRatio(contentMode: .fill))
.edgesIgnoringSafeArea(.vertical)
}
I ended up doing something like this.
Please let me know if there is a better way
NavigationView {
GeometryReader { gr in
ZStack {
VStack(alignment: HorizontalAlignment.center, spacing: 10) {
HStack{
Spacer()
}
Text("1").foregroundColor(.white).padding(EdgeInsets(top: 30, leading: 0, bottom: 0, trailing: 0))
Text("2").foregroundColor(.white)
Spacer()
HStack {
NavigationLink(destination: SigninScreen()){
Text("Button 1")
}
Button(action: {}){
Text("Button 2")
}
}.padding()
}.background(Image("bg-welcome")
.resizable()
.aspectRatio(contentMode: .fill)).edgesIgnoringSafeArea(.all)
}.navigationBarHidden(true)
}
}

Remove circular button background in SwiftUI (WatchKit)

I'm struggling to remove the background of a custom circular Button element in SwiftUI which is defined as follows:
struct NavButton: View {
var body: some View {
Button(action: {})
VStack {
Text("Button")
}
.padding(40)
.background(Color.red)
.font(.title)
.mask(Circle())
}
}
}
This results in a rectangular light gray background around the button, where I want it to not be shown:
I tried to append a "background" modifier to the button, and it demonstrates very strange behavior: if it's set to "Color.clear", there is no effect. But if I set it to "Color.green" it does change the background as expected.
Example of setting the "Background" modifier to "Color.green":
struct NavButton: View {
var body: some View {
Button(action: {})
VStack {
Text("Button")
}
.padding(40)
.background(Color.red)
.font(.title)
.mask(Circle())
}
.background(Color.green) // has no effect if set to "Color.clear"
}
}
I wonder if I'm missing something here?
PS: I'm using Xcode 11.1 (11A1027)
Try adding .buttonStyle(PlainButtonStyle()) on the button itself.
You would have something like this:
Button(action: {}){
VStack{
Text("Button")
}
.padding(40)
.background(Color.red)
.font(.headline)
.mask(Circle())
}
.buttonStyle(PlainButtonStyle())
Declare your own ButtonStyle:
struct RedRoundButton: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(40)
.font(.title)
.background( Circle()
.fill(Color.red))
}
}
and then use it like this:
Button("Button") {}
.buttonStyle(RedRoundButton())
Try this:
struct ContentView: View {
var body: some View {
Button(action: {}) {
Text("Button")
.frame(width: 80, height: 80)
}
.background(Color.red)
.cornerRadius(40)
.frame(width: 80, height: 80)
}
}
Try this.
struct ContentView: View {
var body: some View {
VStack {
Button(action: {}){
Text("button")
.font(.system(size: 50))
.foregroundColor(.black)
.bold()
}
.padding(30)
.background(Color.yellow)
.font(.headline)
.mask(Circle())
.buttonStyle(PlainButtonStyle())
} // end Vstack
}// end body
}

Resources