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())
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…