WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

[SOLVED]Problem with position() / offset()

Forums > SwiftUI

I`m trying to move this circle to the edges of the screen then determine if it is at the border of the screen and show alert.

This is what I already tried: Tried offset(), now am playing with position() without luck. Tried using geometryReader didnt help

I can hard code to a value of minus something which is working but want to know how to detect the edges of the screen and also to understand why this logic isnt working.

To know edges of the screen I tried also using UIScreen.main.boundries

I`m doing SwiftUI excersizes to get "comfortable" with SwiftUI which is a real pain.

//
//  ContentView.swift
//  MoveTheBall
//
//

import SwiftUI

struct ContentView: View {
    let buttons1 = ["RESET","UP","COLOR"]
    let buttons2 = ["<","DOWN",">"]
    @State private var colorSelector = 0
    let circleColors:[Color] = [.red,.green,.blue,.black]
    @State private var ballOffset = CGPoint.init(x: 80, y: 80)
    @State private var circleOpacity = 0.5
    @State private var alertActive = false

    var body: some View {

            ZStack{
                Color.init("Grayish")
                VStack{
                    Circle()
                        .fill(circleColors[colorSelector]).opacity(circleOpacity)
                        .position(ballOffset)
                        .frame(width: 160, height: 160)
                }

                VStack(spacing:10){
                    Spacer()

                    Slider(value: $circleOpacity)

                    HStack{
                        ForEach(0..<buttons1.count,id:\.self){ text in
                            Button(action: {
                                switch text{
                                case 0:
                                    colorSelector = 0
                                    ballOffset = .zero

                                case 1:
                                    ballOffset.y -= 3

                                case 2:
                                    if colorSelector == circleColors.count - 1{
                                            colorSelector = 0
                                        }
                                        else {
                                            colorSelector += 1
                                        }
                                default: break
                                }

                            }, label: {
                                Text(buttons1[text])
                                    .foregroundColor(text == 1 ? Color.white:Color.accentColor)

                            })
                            .buttonModifier()
                            .background(RoundedRectangle(cornerRadius: 10).fill(Color.accentColor).opacity(text == 1 ? 1 : 0))

                        }
                    }.padding(.horizontal,5)

                    HStack{
                        ForEach(0..<buttons2.count,id:\.self){text in
                            Button(action:{
                                switch text{
                                case 0:
                                    ballOffset.x -= 3

                                case 1:
                                    ballOffset.y += 3

                                case 2:
                                    ballOffset.x += 3
                                default:break
                                }
                            },
                            label:{
                                Text(buttons2[text])
                                    .foregroundColor(Color.white)
                            })
                            .buttonModifier()
                            .background(RoundedRectangle(cornerRadius: 10).fill(Color.blue))
                        }
                    }.padding([.bottom,.horizontal],5)

                }
                .alert(isPresented: $alertActive, content: {
                    Alert(title: Text("out of bounds"), message: Text("out"), dismissButton: .default(Text("OK")))
                })
            }.edgesIgnoringSafeArea(.all)

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ButtonModifier: ViewModifier{
    func body(content: Content) -> some View {
        content
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 44, idealHeight: 44, maxHeight: 44)
            .padding(.horizontal)
            .foregroundColor(Color.accentColor)
            .background(RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.accentColor))

    }
}

extension View{
    func buttonModifier() -> some View{
        modifier(ButtonModifier())
    }
}

3      

Solved: Better solution to this problem available on stackoverFlow. [https://stackoverflow.com/questions/65512250/problem-with-position-offset-swiftui]

//
//  ContentView.swift
//  MoveTheBall
//
//

import SwiftUI

struct ContentView: View {
    let buttons1 = ["RESET","UP","COLOR"]
    let buttons2 = ["<","DOWN",">"]
    let circleColors:[Color] = [.red,.green,.blue,.black]

    @State private var colorSelector = 0
    @State private var ballOffset = CGPoint.init(x: 80, y: 80)
    @State private var circleOpacity = 0.5
    @State private var alertActive = false

    var body: some View {
        GeometryReader{geometry in
            ZStack{
                Color.init("Grayish")
                VStack{
                    Circle()
                        .fill(circleColors[colorSelector]).opacity(circleOpacity)
                        .position(ballOffset)
                        .frame(width: geometry.size.width / 2, height: geometry.size.height / 2)
                }

                VStack(spacing:10){
                    Spacer()

                    Slider(value: $circleOpacity)

                    HStack{
                        ForEach(0..<buttons1.count,id:\.self){ text in
                            Button(action: {
                                switch text{
                                case 0:
                                    colorSelector = 0
                                    ballOffset = CGPoint(x: 80,y: 80)

                                case 1:
                                    if ballOffset.y > 0 {
                                    ballOffset.y -= geometry.size.height / 100
                                    }
                                    else {
                                        alertActive = true
                                        ballOffset.y = 80
                                    }
                                case 2:
                                    if colorSelector == circleColors.count - 1{
                                        colorSelector = 0
                                    }
                                    else {
                                        colorSelector += 1
                                    }
                                default: break
                                }

                            }, label: {
                                Text(buttons1[text])
                                    .foregroundColor(text == 1 ? Color.white:Color.accentColor)

                            })
                            .buttonModifier()
                            .background(RoundedRectangle(cornerRadius: 10).fill(Color.accentColor).opacity(text == 1 ? 1 : 0))

                        }
                    }.padding(.horizontal,5)

                    HStack{
                        ForEach(0..<buttons2.count,id:\.self){text in
                            Button(action:{
                                switch text{
                                case 0:
                                    if ballOffset.x > 0 {
                                    ballOffset.x -= geometry.size.width / 100
                                    }
                                    else {
                                        alertActive = true
                                        ballOffset.x = 80
                                    }

                                case 1:
                                    if ballOffset.y < geometry.size.height / 2{
                                    ballOffset.y += geometry.size.height / 100
                                    }
                                    else {
                                        alertActive = true
                                        ballOffset.y = 80
                                    }
                                case 2:
                                    if ballOffset.x < geometry.size.width / 2{
                                    ballOffset.x += geometry.size.width / 100
                                    }
                                    else{
                                        alertActive = true
                                        ballOffset.x = 80
                                    }
                                default:break
                                }
                            },
                            label:{
                                Text(buttons2[text])
                                    .foregroundColor(Color.white)
                            })
                            .buttonModifier()
                            .background(RoundedRectangle(cornerRadius: 10).fill(Color.blue))
                        }
                    }.padding([.bottom,.horizontal],5)

                }
                                .alert(isPresented: $alertActive, content: {
                                    Alert(title: Text("Out of bounds"), message: Text("Returning to initial position"), dismissButton: .default(Text("OK")))
                                })
            }.edgesIgnoringSafeArea(.all)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ButtonModifier: ViewModifier{
    func body(content: Content) -> some View {
        content
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 44, idealHeight: 44, maxHeight: 44)
            .padding(.horizontal)
            .foregroundColor(Color.accentColor)
            .background(RoundedRectangle(cornerRadius: 10)
                            .stroke(Color.accentColor))

    }
}

extension View{
    func buttonModifier() -> some View{
        modifier(ButtonModifier())
    }
}

3      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.