Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

swift - Problem with position() / offset() 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 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())
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
        }
    }
    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...