I'd like to use the navigation link.Newbie Wang is in the process of hair loss - swift

I want to use Navigationlink. I've been a novice for 2 weeks since I started.I am currently learning SwiftUi.
I created "OnboredView" after watching YouTube, but I don't know how to connect "OnboredView" to "CountentView".
NavigationView(){
NavigationLink(destination: OnboardView())
I learned how to make it like this through YouTube, but I don't know what to do now. I put it here and there, but the red errors bother me.
Tell me how to connect "NavigationLink" by pressing the button on "CountentView".
I'd like to click "Chevron.Light" to move on to "OnboredView."And if possible, please let me know how I can get rid of the "onboard screen" on the second run?
I am not good at English.I'm sorry. I'm experiencing hair loss again.
import SwiftUI
struct ContentView: View {
#State private var animate: Bool = false
var body: some View {
ZStack{
ZStack{
Image("rogo1")
.resizable()
.frame(width: 75, height: 75)
.offset(y: animate ? -100 : 0)
}
ZStack{
Image("rogo2")
.resizable()
.frame(width: 75, height: 75)
.offset(y: animate ? -100 : 0)
}
VStack {
HStack {
Spacer()
Image("images (1)")
.resizable()
.frame(width: 300, height: 300)
.offset(x: animate ? 300 : 150, y: animate ? -300 : -150)
}
Spacer()
HStack {
Image("images (1)")
.resizable()
.frame(width: 400, height: 400)
.offset(x: animate ? -500 : -150, y: animate ? 500 : 150)
Spacer()
}
}
ZStack(alignment: .bottom){
GeometryReader { g in
VStack (alignment: .leading, spacing: 20){
Text("안녕하세요!")
.font(.title)
.fontWeight(.semibold)
.padding(.top, 20)
//인삿말과 회원가입
Text("기분 좋은 매일습관을 만들기 위한 앱 ( ) 입니다! 시간표와 더불어 루틴을 함께 할수
있도록 설계 되었습니다.저희 ( )와 함께 계획해봐요!")
.fontWeight(.medium)
.multilineTextAlignment(.center)//중앙으로 결집
.padding(5)
ZStack {
Button(action: {},label: {
Image(systemName: "chevron.right")
.font(.system(size:20, weight: .semibold))
.frame(width: 60, height: 60)
.foregroundColor(.black)
.background(Color.white)
.clipShape(Circle())
.overlay(
ZStack {
Circle()
.stroke(Color.black.opacity(0.04),lineWidth: 4)
Circle()
.trim(from: 0, to: 0.03)
.stroke(Color.white,lineWidth: 4)
.rotationEffect(.init(degrees: -40))
})
})
.padding(-10)
}
Spacer()
}
.frame(maxWidth: .infinity)
.padding(.horizontal, 30)
.background(Color.green)
.clipShape(CustomShape(leftCorner: .topLeft, rightCorner: .topRight,
radii: 20))
.offset(y: animate ? g.size.height : UIScreen.main.bounds.height)
}
}.frame(height: 275)
//여기까지 짤라도 됨 온보드
}
.frame(maxWidth: .infinity)
.edgesIgnoringSafeArea(.all)
.onAppear(perform: {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
withAnimation(Animation.easeOut(duration: 0.45)){
animate.toggle()
}
}
})
}
{
struct CustomShape: Shape {
var leftCorner: UIRectCorner
var rightCorner: UIRectCorner
var radii: CGFloat
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners:
[leftCorner,rightCorner], cornerRadii: CGSize(width: radii, height: radii))
return Path(path.cgPath)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
Group {
}
}
}
}
import SwiftUI
struct OnboardView: View {
#AppStorage("currentPage") var currentPage = 1
var body: some View {
if currentPage > totalPages {
Home()
}else{
WalkthroughScreen()
}
}
}
struct OnboardView_Previews: PreviewProvider {
static var previews: some View {
OnboardView()
}
}
struct Home: View {
var body: some View{
Text("welcome To Home!!!")
.font(.title)
.fontWeight(.heavy)
}
}
//..Walkthrough Screen..
struct WalkthroughScreen: View {
#AppStorage("currentPage") var currentPage = 1
var body: some View {
//For Slide Animation
ZStack{
//Changing Between Views..
if currentPage == 1 {
ScreenView(image: "image1", title: "Step1", detail: "", bgColor:
Color(.white))
//transition(.scale)영상에서는 넣었으나 오류가나서 사용하지 못함
}
if currentPage == 2 {
ScreenView(image: "image2", title: "Step2", detail: "", bgColor:
Color(.white))
}
if currentPage == 3 {
ScreenView(image: "image3", title: "Step3", detail: "아니 ㅡㅡ 이런 방법이 유레카",
bgColor: Color(.white))
}
}
.overlay(
Button(action: {
//changing views
withAnimation(.easeInOut){
if currentPage < totalPages {
currentPage += 1
}else{
currentPage = 1
//For app testing ONly
}
}
}, label: {
Image(systemName: "chevron.right")
.font(.system(size: 20, weight: .semibold))
.foregroundColor(.black)
.frame(width: 60, height: 60)
.clipShape(Circle())
//strclulat Slider
.overlay(
ZStack{
Circle()
.stroke(Color.black.opacity(0.04),lineWidth: 4
Circle()
.trim(from: 0, to: CGFloat(currentPage) /
CGFloat(totalPages))
.stroke(Color.green,lineWidth: 4)
.rotationEffect(.init(degrees: -99))
}
.padding(-15)
)
})
.padding(.bottom,20)
,alignment: .bottom
)
}
}
struct ScreenView: View {
var image: String
var title: String
var detail: String
var bgColor: Color
#AppStorage("currentPage") var currentPage = 1
var body: some View {
VStack(spacing:20){
HStack {
//Showing it only for first page..
if currentPage == 1{
Text("Hello Members!")
.font(.title)
.fontWeight(.semibold)
//Letter Spacing
.kerning(1.4)
}else{
//Back Butten..
Button(action: {
withAnimation(.easeInOut){
currentPage -= 1
}
}, label: {
Image(systemName: "chevron.left")
.foregroundColor(.white)
.padding(.vertical,10)
.padding(.horizontal)
.background(Color.black.opacity(0.4))
.cornerRadius(10)
})
}
Spacer()
Button(action: {
withAnimation(.easeInOut){
currentPage = 4
}
}, label: {
Text("Skip")//글자입력
.fontWeight(.semibold)//글자 폰트변경
.kerning(1.2)//글자간 간격 조정
})
}
.foregroundColor(.black)//그라운드 컬러 변경
.padding()
Spacer(minLength: 0)//수평,수직 줄바꿈
Image(image)//이미지 삽입
.resizable()//크기 확대
.aspectRatio(contentMode: .fit)//이미지 크기
Text(title)
.font(.title)//폰트 크기변경
.fontWeight(.bold)//폰트 두께 변경
.foregroundColor(.black)//색깔 변경
.padding(.top)
//Change with your Own Thing..
Text(detail)
.fontWeight(.semibold)
.kerning(1.3)//자간조정
.multilineTextAlignment(.center)//텍스트를 중앙으로 결집
Spacer(minLength: 220)//minimun Spacing When phone is reducing수직위치 조정
}
.background(bgColor.cornerRadius(10).ignoresSafeArea())
}
}
var totalPages = 3

Related

Zoom Image over top of other Views SwiftUI

I have a image as thumbnail when image is tapped it should be expanded/zoom at the centre of screen with background as blur. I tried scale effect but the image is not on top of other view but looks like behind (see pics). How to achieve this zoomed imaged with blur background effect (see peacock pic this is the requirement)
#State var enlarge:Bool = false
var body: some View {
GeometryReader{geo in
VStack{
ZStack(alignment: .top){
LinearGradient(gradient:Gradient(colors: [.blue.opacity(0.3),.blue.opacity(0.2)]),startPoint: .top,endPoint:.bottom)
.ignoresSafeArea()
VStack(alignment: .leading,spacing :5){
HStack{
Text("Lorum Ipsum ackndweg")
.fontWeight(.semibold)
.padding(.top,15)
.padding(.leading,18)
.foregroundColor(ThemeColor.testName)
}
.frame(width: geo.size.width, alignment: .leading)
Image("capAm")
.resizable()
.scaledToFit()
.frame(width: 40, height: 40)
.padding(.leading,18)
.onTapGesture{
withAnimation
{
self.enlarge.toggle()
}
}
.scaleEffect(self.enlarge ? 4 : 1,anchor: .topLeading)
VStack(alignment:.leading,spacing: 5){
HStack{
Text("Turn Around Time :")
.font(.system(size: 14))
.foregroundColor(.red)
Text("Report Delivery : Daily")
.font(.system(size: 14))
.foregroundColor(.orange)
}
.frame(width: geo.size.width, alignment: .center)
VStack(alignment:.leading)
{
HStack{
Text("Turn Around Time(TAT) :")
.font(.system(size: 14))
.foregroundColor(.red)
Text("4 hours after acceptance of the sample at the centre")
.font(.system(size: 14))
.foregroundColor(.red)
.multilineTextAlignment(.leading)
}
}.frame(width: geo.size.width, alignment: .center)
}
}}}}}}
below just an idea
struct SwiftUIView: View {
#State private var enlarge = false
#State private var list = 1...10
#State private var current = 0
var body: some View {
ZStack {
ZStack {
Image(systemName: "\(current).circle")
.resizable()
.scaledToFit()
.frame(width: 60 , height: 60)
.padding()
.animation(.spring(), value: enlarge)
.foregroundColor(.yellow)
}
.frame(width: 300,
height: 200)
.background(Color.black.opacity(0.2))
.foregroundColor(Color.clear)
.cornerRadius(20)
.transition(.slide)
.opacity(self.enlarge ? 1 : 0)
.zIndex(2)
.onTapGesture{
withAnimation {
self.enlarge.toggle()
}
}
List {
ForEach(list, id:\.self) { i in
Label("detail of \(i)", systemImage: "\(i).circle")
.onTapGesture{
current = i
withAnimation {
self.enlarge.toggle()
}
}
}
}
.blur(radius: self.enlarge ? 3 : 0).offset(y: 1)
}
.onTapGesture{
withAnimation {
self.enlarge = false
}
}
}
}

SwiftUI, different Views in same GridView

I need to add two different types of view in same grid view, there is an alignment issue between these view as shown in give image below. The view which contains image is taking more space from top and bottom even after fixing the size
struct TestView: View {
#StateObject var vm = BusinessProfileViewModel()
#Environment(\.presentationMode) private var presentationMode
let columns = [
GridItem(.flexible(minimum: 100), spacing: 20),
GridItem(.flexible(minimum: 100), spacing: 20)
]
var body: some View {
loadView()
}
}
extension TestView {
func loadView() -> some View {
GeometryReader { geometry in
ZStack(alignment: .bottomTrailing) {
ScrollView(.vertical, showsIndicators: false) {
topBusinessImage(geometry: geometry)
VStack {
featureProduct(geometry: geometry)
}.padding()
}.edgesIgnoringSafeArea(.top)
}
}
}
func topBusinessImage(geometry: GeometryProxy) -> some View {
VStack(spacing: 0) {
// Profile Image Stack
// Banner Zstack
ZStack (alignment: .top) {
Image(ImageName.productPlaceholder.rawValue)
.resizable()
.frame(height: geometry.size.height / 2.5)
}
}
}
func featureProduct(geometry: GeometryProxy) -> some View {
VStack(alignment: .leading) {
// product and services button
HStack {
Text("Products & Services")
.font(.custom(Popins.bold.rawValue, size: 20))
Spacer()
Button {
print("list")
} label: {
Image(ImageName.list.rawValue)
.resizable()
.frame(width: 24, height: 24)
}.padding(5)
}
LazyVGrid(columns: columns, spacing: 30) {
BusinessProductCell()
ProductOnlyDetailCell()
ProductOnlyDetailCell()
BusinessProductCell()
}
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
view that contains image
import SwiftUI
struct BusinessProductCell: View {
var body: some View {
loadView()
}
}
extension BusinessProductCell {
func loadView() -> some View {
VStack(alignment: .leading) {
ZStack(alignment: .topLeading) {
Image(ImageName.business.rawValue)
.resizable()
.frame(height: 205)
.cornerRadius(10)
HStack {
Button {
print("fav")
} label: {
Image(systemName: "heart.fill")
.resizable()
.scaledToFit()
.foregroundColor(UnifiedColor.blue)
.frame(width: 20, height: 20)
}.padding()
Spacer()
Button {
print("fav")
} label: {
Image(systemName: "ellipsis")
.resizable()
.scaledToFit()
.frame(width: 20)
.foregroundColor(.white)
}.padding()
}
}
Text("Dove Body Care")
.foregroundColor(.black)
.font(.custom(Popins.medium.rawValue, size: 16))
HStack {
Text("$49.99")
.font(.custom(Popins.medium.rawValue, size: 12))
.foregroundColor(UnifiedColor.textBlue)
Spacer()
HStack {
Text("(286 Favorites)")
.font(.custom(Popins.regular.rawValue, size: 8))
.foregroundColor(.gray)
Image(ImageName.heart_line.rawValue)
.resizable()
.frame(width: 15, height: 15)
}
}
}
}
}
struct BusinessProductCell_Previews: PreviewProvider {
static var previews: some View {
BusinessProductCell()
.frame(width: 200, height: 250)
}
}
View that only contains text or second view for gird view
struct ProductOnlyDetailCell: View {
var body: some View {
loadView()
}
}
extension ProductOnlyDetailCell {
func loadView() -> some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Image(ImageName.productPlaceholder.rawValue)
.resizable()
.scaledToFill()
.frame(width: 24, height: 24)
.clipShape(Circle())
.overlay {
Circle().stroke(.white, lineWidth: 1)
}
Text("Anton Jr.")
.font(.custom(Popins.regular.rawValue, size: 12 ))
.foregroundColor(.black)
.lineLimit(1)
Spacer()
Button {
print("more btn")
} label: {
Image(systemName: "ellipsis")
.resizable()
.foregroundColor(.black)
.frame(width: 18, height: 4)
.padding([.trailing, .top, .bottom])
}
}
Text("DJ for night")
.font(.custom(Popins.bold.rawValue, size: 14))
.foregroundColor(.black)
Text("Lorem ipsum dolor sitamet, consectetur adipiscingelit. Lectus idcommodoegestas metusinterdum dolor.")
.multilineTextAlignment(.leading)
.font(.custom(Popins.regular.rawValue, size: 12))
.foregroundColor(.black)
.opacity(0.8)
Spacer()
HStack (spacing: 0){
Text("$15K")
.font(.custom(Popins.bold.rawValue, size: 14))
.foregroundColor(.black)
Text("/")
.font(.custom(Popins.bold.rawValue, size: 14))
.foregroundColor(.gray)
Text("Night")
.font(.custom(Popins.regular.rawValue, size: 14))
.foregroundColor(.gray)
}
Text("25 minute ago")
.font(.custom(Popins.regular.rawValue, size: 10))
.foregroundColor(.gray)
}
.padding(10)
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.gray.opacity(0.1))
)
}
}

Swift, Stuck on making an notes app, don't know what the problem is using text editor

I am new to coding and am trying to make a notes app come to life, the issue is I have no idea how to make separate text editors in my for loops.
This is my code. When you run the project and create a green sticky note and type on it, it works fine, but if you do a second one of the same color, they have the same text. How do I fix this in a way that doesn't take hours of tedious work?
I have tried to use different ways to make a for loop. I have made one with normal lists and with a struct list that has different ids, both come up with the same text editor.
(Text editors don't copy over color, which makes me think it's the for loop because when I tried to use different variables for the bindings it didn't work either.)
//
// ContentView.swift
// Notesapp
//
//
import SwiftUI
import Foundation
struct newBoy: Identifiable {
let id = UUID()
let number: Int
}
class NewBoys: ObservableObject {
#Published var numbs = [newBoy]()
}
struct ContentView: View {
#StateObject var numbers1 = NewBoys()
#State var buttonoff = true
#State var recaddor: [GridItem] = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
]
#State var glist = [Int]()
#State var i = -1
#State var gtext = "This be me"
#State var blist = [Int]()
#State var bman = -1000
#State var btext = "Enter your notes here!"
#State var bklist = [Int]()
#State var bkman = -2000
#State var bktext = "Enter your notes here!"
#State var ylist = [Int]()
#State var yman = -3000
#State var ytext = "Enter your notes here!"
#State var olist = [Int]()
#State var oman = -4000
#State var otext = "Enter your notes here!"
#State var plist = [Int]()
#State var pman = -5000
#State var ptext = "Enter your notes here!"
var body: some View {
HStack{
VStack {
Text("Make new note!").padding().foregroundColor(Color.black)
Button {
withAnimation(.easeIn) {
self.buttonoff.toggle()
}
} label: {
Image(systemName: "plus")
.font(.title2)
.foregroundColor(.white)
.rotationEffect(.init(degrees: buttonoff ? 0 : 45))
.scaleEffect(buttonoff ? 1 : 1.3)
.padding()
}.buttonStyle(PlainButtonStyle())
.background(Color.black)
.clipShape(Circle())
.padding()
if buttonoff {
}
else {
Group {
Button {
recGreen()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.green)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
Button {
recBlue()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.blue)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
Button {
recBlack()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.black)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
Button {
recYellow()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.yellow)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
Button {
recOrange()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.orange)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
Button {
recPurple()
} label: {
RoundedRectangle(cornerRadius: 25)
.fill(Color.purple)
.frame(width: 30, height: 30)
}.buttonStyle(PlainButtonStyle())
}.padding(20)
.scaleEffect(1.5)
}
}.frame(width: 100, height: 700, alignment: .top)
.background(Color.white)
.border(Color.gray, width: 2)
VStack {
ScrollView{
LazyVGrid(columns: recaddor){
ForEach(numbers1.numbs, id: \.id) {o in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.green)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
print("hi")
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $gtext)
.frame(width: 225, height: 150, alignment: .center)
.cornerRadius(3.0)
.colorMultiply(.green)
Spacer()
}
}
}
ForEach(blist, id: \.self) {blueman in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.blue)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
blist = blist.filter({ Int in
return Int != blueman
})
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $btext)
Spacer()
}
}
}
ForEach(bklist, id: \.self) {bklueman in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.black)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
bklist = bklist.filter({ Int in
return Int != bklueman
})
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $bktext)
Spacer()
}
}
}
ForEach(ylist, id: \.self) {ylueman in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.yellow)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
ylist = ylist.filter({ Int in
return Int != ylueman
})
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $ytext)
Spacer()
}
}
}
ForEach(olist, id: \.self) {olueman in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.orange)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
olist = olist.filter({ Int in
return Int != olueman
})
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $otext)
Spacer()
}
}
}
ForEach(plist, id: \.self) {plueman in
ZStack{
RoundedRectangle(cornerRadius: 25)
.fill(Color.purple)
.frame(width: 250, height: 200)
.padding()
VStack{
HStack{
Spacer()
Button {
plist = plist.filter({ Int in
return Int != plueman
})
} label: {
Image(systemName: "minus")
}
.padding(.top, 25.0)
.padding(.trailing, 30.0)
.frame(alignment:.trailing)
}
TextEditor(text: $ptext)
Spacer()
}
}
}
}
}
}.frame(width: 1100)
}
}
func recGreen() {
let i = newBoy(number: 0)
numbers1.numbs.append(i)
print(numbers1.numbs)
}
func recBlue() {
bman += 1
blist.append(bman)
}
func recBlack() {
bkman += 1
bklist.append(bkman)
}
func recYellow() {
yman += 1
ylist.append(yman)
}
func recOrange() {
oman += 1
olist.append(oman)
}
func recPurple() {
pman += 1
plist.append(pman)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
It's because you are using the same binding.
In your ForEach, you are creating multiple TextEditors but they are editing the same variable like $otext. You need to create a struct that holds the text, and the array you use in the ForEach should be of type YourStruct. Then you pass the text to TextEditors.
struct Note: Identifiable {
var id: Int //your current array type, i.e if your array is [Int] use Int.
var text: String //this is the text to pass to the editors
}

Make SwiftUI Rectangle same height or width as another Rectangle

For a SwiftUI layout in a macOS app, I have three Rectangles as shown below:
The code to produce this layout is:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
HStack {
ZStack {
Rectangle()
.fill(Color.purple)
.frame(width: 20)
Text("1")
.font(.subheadline)
.foregroundColor(.white)
}
ZStack {
Rectangle()
.fill(Color.orange)
Text("2")
.font(.subheadline)
.foregroundColor(.white)
}
}
HStack {
ZStack {
Rectangle()
.fill(Color.red)
.frame(height: 20)
Text("3")
.font(.subheadline)
.foregroundColor(.white)
}
}
}
.frame(minWidth: 400, minHeight: 250)
}
}
My objective is for Rectangle 1 to be the same height as Rectangle 2 and for Rectangle 3 to be the same width as Rectangle 2. The size relationships between the rectangles should stay the same as the window size is changed. When done correctly, the final result should look like the following:
How can I accomplish this in SwiftUI?
Here is a working approach, based on view preferences. Tested with Xcode 11.4 / macOS 10.15.6
struct ViewWidthKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = value + nextValue()
}
}
struct ContentView: View {
#State private var boxWidth = CGFloat.zero
var body: some View {
VStack {
HStack {
ZStack {
Rectangle()
.fill(Color.purple)
.frame(width: 20)
Text("1")
.font(.subheadline)
.foregroundColor(.white)
}
ZStack {
Rectangle()
.fill(Color.orange)
Text("2")
.font(.subheadline)
.foregroundColor(.white)
}
.background(GeometryReader {
Color.clear.preference(key: ViewWidthKey.self,
value: $0.frame(in: .local).size.width) })
}
HStack {
ZStack {
Rectangle()
.fill(Color.red)
.frame(height: 20)
Text("3")
.font(.subheadline)
.foregroundColor(.white)
}.frame(width: boxWidth)
}.frame(maxWidth: .infinity, alignment: .bottomTrailing)
}
.onPreferenceChange(ViewWidthKey.self) { self.boxWidth = $0 }
.frame(minWidth: 400, minHeight: 250)
}
}

How to change view with Navigationlink with two conditions in SwiftUI?

I have 3 buttons in my view. I want to change view with navigationlink when 2 buttons are active. When I tap to tap1 and tap3 I want to go to ViewOne(), when I tap to tap2 and tap3 I want to ViewTwo() How can I do that ?
#State var tap1 : Bool = false
#State var tap2 : Bool = false
#State var tap3 : Bool = false
NavigationLink(destination: ViewOne(), isActive: $tap1, label: {
VStack{
Image("smile")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Fine")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
NavigationLink(destination: ViewTwo(), isActive: $tap2) {
VStack{
Image("sad")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Bad")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
NavigationLink(destination: ?(), isActive: $tap3) {
Text("Continue")
You can try the following:
struct ContentView: View {
#State var tap1: Bool = false
#State var tap2: Bool = false
#State var isLinkActive: Bool = false
var body: some View {
NavigationView {
VStack {
button1
button2
button3
}
}
}
var button1: some View {
Button(action: {
self.tap1.toggle()
}) {
VStack {
Image("smile")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Fine")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
}
.background(tap1 ? Color.green : .clear)
}
var button2: some View {
Button(action: {
self.tap2.toggle()
}) {
VStack {
Image("sad")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Bad")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
}
.background(tap2 ? Color.red : .clear)
}
var button3: some View {
Button(action: {
// make sure you set the link only when ready
// what should happen if tap1 and tap2 are true?
self.isLinkActive.toggle()
}) {
Text("Continue")
}
.background(
NavigationLink(destination: destinationView, isActive: $isLinkActive) {
EmptyView()
}
.hidden()
)
}
#ViewBuilder
var destinationView: some View {
if tap1 {
Text("ViewOne")
} else if tap2 {
Text("ViewTwo")
}
}
}