0

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 exersises to get "comfortable" with SwiftUI which is a real pain.

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 // wall problem 

    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")))
                }) // alert not working have to figure out wall problem first
            }.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())
    }
}
Surepic
  • 13
  • 5
  • You need to use named coordinate space on external ZStack and GeometryReader to get coordinates of ball in that namespace to validate them. Next should be helpful https://stackoverflow.com/a/60495440/12299030. – Asperi Dec 30 '20 at 19:13
  • The alert will only present when you toggle showAlert to true. I don't see anywhere in your code that's toggling showAlert? – nicksarno Dec 30 '20 at 21:50
  • @nicksarno alert is working i commented it out and took out portion of the code which is responsible for switching the state. The problem is with walls or boundaries of the frame. So far cant solve that problem. – Surepic Dec 30 '20 at 22:52
  • Referencing UIScreen.main.bounds is working for me. Sorry, I'm a bit confused what the issue is? – nicksarno Dec 30 '20 at 23:45
  • Problem is that i dont want to hardcode bound limits. I.e. width 100 const something (cgfloat/cgsize/cgpoint) but want it to be dynamic. Like geometryreader is doing so there are no constants fixed there any screen will work. With UIScreenbound again i have to tie upper/lower/left/right limits to a constant i cant do it dynamically. If u will compile my code u will see that u can easily go passed the screen boundaries. – Surepic Dec 31 '20 at 00:00
  • So are you ok with using GeometryReader then? – nicksarno Dec 31 '20 at 00:07

1 Answers1

0

Here is a solution using GeometryReader, which is dynamic and will change with the device orientation. It checks the future ball position is within the boundaries before moving the ball and shows the alert on failure.

struct ContentView: View {
    let buttons1 = ["RESET","UP","COLOR"]
    let buttons2 = ["<","DOWN",">"]
    @State private var colorSelector = 0
    let circleColors:[Color] = [.red,.green,.blue,.black]
    let ballSize = CGSize(width: 160, height: 160)
    @State private var ballOffset: CGSize = .zero
    @State private var circleOpacity = 0.5
    @State private var alertActive = false

    var body: some View {
            ZStack {
                Color.green.opacity(0.4)
                    .edgesIgnoringSafeArea(.all)
                
                Circle()
                    .fill(circleColors[colorSelector])
                    .opacity(circleOpacity)
                    .frame(width: ballSize.width, height: ballSize.height)
                    .offset(ballOffset)

                GeometryReader { geometry in
                    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:
                                        handleMove(incrementY: -3, geometryProxy: geometry)
                                    case 2:
                                        colorSelector = colorSelector == (circleColors.count - 1) ? 0 : 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:
                                        handleMove(incrementX: -3, geometryProxy: geometry)
                                    case 1:
                                        handleMove(incrementY: 3, geometryProxy: geometry)
                                    case 2:
                                        handleMove(incrementX: 3, geometryProxy: geometry)
                                    default:break
                                    }
                                },
                                label:{
                                    Text(buttons2[text])
                                        .foregroundColor(Color.white)
                                })
                                .buttonModifier()
                                .background(RoundedRectangle(cornerRadius: 10).fill(Color.blue))
                            }
                        }.padding([.bottom,.horizontal],5)

                    }
                    .background(Color.orange.opacity(0.5))
                }

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

    }
    
    
    func handleMove(incrementX: CGFloat = 0, incrementY: CGFloat = 0, geometryProxy: GeometryProxy) {

        let newOffset = CGSize(width: ballOffset.width + incrementX, height: ballOffset.height + incrementY)
        
        let standardXOffset =
            (geometryProxy.size.width) / 2 // width (excluding safe area)
            - (ballSize.width / 2) // subtract 1/2 of ball width (anchor is in the center)
        let maxXOffset = standardXOffset + geometryProxy.safeAreaInsets.trailing // + trailing safe area
        let minXOffset = -standardXOffset - geometryProxy.safeAreaInsets.leading // + leading safe area

        let standardYOffset =
            (geometryProxy.size.height / 2) // height (excluding safe area)
            - (ballSize.height / 2) // subtract 1/2 of ball height (anchor is in the center)
        let maxYOffset = standardYOffset + geometryProxy.safeAreaInsets.bottom // + bottom safe area
        let minYOffset = -standardYOffset - geometryProxy.safeAreaInsets.top // + top safe area
        
        if
            (newOffset.width >= maxXOffset) ||
            (newOffset.width <= minXOffset) ||
            (newOffset.height >= maxYOffset) ||
            (newOffset.height <= minYOffset) {
            alertActive.toggle()
        } else {
            ballOffset = newOffset
        }
    }
    
}
nicksarno
  • 3,850
  • 1
  • 13
  • 33
  • 1
    I finished my implementation of the problem using geometryReader as suggested and it works. But after reading your code now it makes much more sense what I couldn't understand. – Surepic Dec 31 '20 at 04:08
  • I copied and pasted this into a new SwiftUI Project (XCode Version 12.5 ) but got the message "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" :( – Mark Highton Ridley Jun 06 '21 at 21:42