How to use self.offset to drag sidemenu in swiftui? - swiftui

I have the following code for my side menu but I'm not able to set self.offset(x:, y:) as it says that the result is unused? How can I make this work as I want the menu to be draggable to the left.
#Binding var showMenu: Bool
var body: some View {
HStack {
GeometryReader { geometry in
MenuView()
.frame(width: 240, alignment: .leading)
.background(Color.white)
.offset(x: self.showMenu ? 0 : -geometry.size.width)
.animation(.spring())
.transition(.move(edge: .leading))
.zIndex(4)
.gesture(DragGesture()
.onChanged { val in
self.offset(x: val.translation.width)
}
.onEnded { val in
self.offset(x: .zero)
}
)
}
}
}

As code is not testable, so just idea - scratchy. You cannot use self of View struct, change instead some state and use that state value in corresponding modifiers, like below
#Binding var showMenu: Bool
#State private var xOffset: CGFloat = .zero
var body: some View {
HStack {
GeometryReader { geometry in
MenuView()
.frame(width: 240, alignment: .leading)
.background(Color.white)
.offset(x: self.showMenu ? xOffset : -geometry.size.width)
.animation(.spring())
.transition(.move(edge: .leading))
.zIndex(4)
.gesture(DragGesture()
.onChanged { val in
self.xOffset = val.translation.width
}
.onEnded { val in
self.xOffset = .zero
}
)
}
}
}

Related

SwiftUI: Double picker wheels with system behavioral

I want to recreate system picker behavioral with two options in wheels with SwiftUI and faced ton of problem. Some of this I solved but some still unsolved. I have pop-ups with different views inside. One of the view it's a DatePicker with displayedComponents: .hourAndMinute. And other one is two Pickers inside HStack. My question is how to make Pickers make look like in system: without white spacing between?
struct MultyPicker: View {
#State var value = 1
#State var value2 = 1
var body: some View {
ZStack(alignment: .bottom) {
Color.black.opacity(0.5)
ZStack {
VStack {
Text("Header")
.font(.title3)
.fontWeight(.bold)
HStack(spacing: 0) {
Picker(selection: $value, label: Text("")) {
ForEach(1..<26) { number in
Text("\(number)")
.tag("\(number)")
}
}
.pickerStyle(WheelPickerStyle())
.compositingGroup()
.clipped(antialiased: true)
Picker(selection: $value2, label: Text("")) {
ForEach(25..<76) { number in
Text("\(number)")
.tag("\(number)")
}
}
.pickerStyle(WheelPickerStyle())
.compositingGroup()
.clipped(antialiased: true)
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 34)
.foregroundColor(.white)
)
}
.padding(.horizontal)
.padding(.bottom, 50)
}
.edgesIgnoringSafeArea([.top, .horizontal])
}
}
// This extension for correct touching area
extension UIPickerView {
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: super.intrinsicContentSize.height)
}
}
Want to achive looks like that with one grey line in selected value
//
// Test2.swift
// Test
//
// Created by Serdar Onur KARADAĞ on 26.08.2022.
//
import SwiftUI
struct Test2: View {
#State var choice1 = 0
#State var choice2 = 0
var body: some View {
ZStack {
Rectangle()
.fill(.gray.opacity(0.2))
.cornerRadius(30)
.frame(width: 350, height: 400)
Rectangle()
.fill(.white.opacity(1))
.cornerRadius(30)
.frame(width: 300, height: 350)
VStack {
Text("HEADER")
HStack(spacing: 0) {
Picker(selection: $choice1, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n)").tag(n)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.clipped()
Picker(selection: $choice2, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n)").tag(n)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.clipped()
}
}
}
}
}
struct Test2_Previews: PreviewProvider {
static var previews: some View {
Test2()
}
}
SwiftUI multi-component Picker basically consists of several individual Picker views arranged horizontally. Therefore, we start by creating an ordinary Picker view for our first component. I am using Xcode version 13.4.1(iOS 15.0).
import SwiftUI
struct ContentView: View {
#State var hourSelect = 0
#State var minuteSelect = 0
var hours = [Int](0..<24)
var minutes = [Int](0..<60)
var body: some View {
ZStack {
Color.black
.opacity(0.5)
.ignoresSafeArea()
.preferredColorScheme(.light)
Rectangle()
.fill(.white.opacity(1))
.cornerRadius(30)
.frame(width: 300, height: 350)
VStack {
Text("Header")
HStack(spacing: 0) {
Picker(selection: $hourSelect, label: Text("")) {
ForEach(0..<self.hours.count) { index in
Text("\(self.hours[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.compositingGroup()
.clipped()
Picker(selection: $minuteSelect, label: Text("")) {
ForEach(0..<self.minutes.count) { index in
Text("\(self.minutes[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(minWidth: 0)
.compositingGroup()
.clipped()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Output :

SwiftUI Crash when calling scrollTo method when view is disappearing

I try to make my ScrollView fixed in a specific place, but the scrollTo method will cause the application to crash.
How to make the ScrollView stay in a fixed place?
I want to control the switching of views by MagnificationGesture to switch from one view to another.
But when Scroll() disappdars, the app crashs.
struct ContentView: View {
#State var tabCount:Int = 1
#State var current:CGFloat = 1
#State var final:CGFloat = 1
var body: some View {
let magni = MagnificationGesture()
.onChanged(){ value in
current = value
}
.onEnded { value in
if current > 2 {
self.tabCount += 1
}
final = current + final
current = 0
}
VStack {
VStack {
Button("ChangeView"){
self.tabCount += 1
}
if tabCount%2 == 0 {
Text("some text")
}else {
Scroll(current: $current)
}
}
Spacer()
HStack {
Color.blue
}
.frame(width: 600, height: 100, alignment: .bottomLeading)
}
.frame(width: 600, height: 400)
.gesture(magni)
}
}
This is ScrollView, I want it can appear and disappear. When MagnificationGesture is changing, scrollview can keep somewhere.
struct Scroll:View {
#Binding var current:CGFloat
let intRandom = Int.random(in: 1..<18)
var body: some View {
ScrollViewReader { proxy in
HStack {
Button("Foreword"){
proxy.scrollTo(9, anchor: .center)
}
}
ScrollView(.horizontal) {
HStack {
ForEach(0..<20) { item in
RoundedRectangle(cornerRadius: 25.0)
.frame(width: 100, height: 40)
.overlay(Text("\(item)").foregroundColor(.white))
.id(item)
}
}
.onChange(of: current, perform: { value in
proxy.scrollTo(13, anchor: .center)
})
}
}
}
}

Adding button to a moving image SwiftUI

I have successfully added a button to an image however when I click the button and the image moves via CGAffineTransform, the image moves but the button stays in the same place. When I click the space where the image used to be before the transform, the state toggle reacts. How do I get the button to move along with the image?
struct SliderView: View {
#State var partyType: Bool = false
var body: some View {
ZStack{
GeometryReader{ geo in
VStack(alignment: .leading){
Button(action: {
withAnimation (){
self.partyType.toggle();
}
}) {
Image("chevronPointer")
.clipped()
.modifier(SlideEffect(offset: CGSize(width: partyType ? geo.size.width - 70 : 0, height: 0.0)))
.animation(.smooth())
.padding(.horizontal)
}
Image("sliderLine")
.resizable()
.scaledToFit()
.frame(width: geo.size.width, alignment: /*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/)
}
}
.frame(height: 40)
}
}
}
struct SlideEffect: GeometryEffect {
var offset: CGSize
var animatableData: CGSize.AnimatableData {
get { CGSize.AnimatableData(offset.width, offset.height) }
set { offset = CGSize(width: newValue.first, height: newValue.second) }
}
public func effectValue(size: CGSize) -> ProjectionTransform {
return ProjectionTransform(CGAffineTransform(translationX: offset.width, y: offset.height))
}
}
struct SliderView_Previews: PreviewProvider {
static var previews: some View {
SliderView()
}
}
Just move the modifier outside the button.
Button(action: {
withAnimation(){
self.partyType.toggle()
}
}) {
Image(systemName: "chevron.up")
.clipped()
.animation(.default)
.padding(.horizontal)
}
.modifier(SlideEffect(offset: CGSize(width: partyType ? geo.size.width - 70 : 0, height: 0.0))) /// here!

SwiftUI DragGesture blocking List vertical scroll?

i am trying to add swipe inside list cell , swipe to show more options such as Delete, archive etc .
The swipe is working just fine , but the List ( vertical scroll ) is no longer scrolling up down .
Cell Bite :
import SwiftUI
struct cl_task: View {
#State private var offset: CGSize = .zero
var body: some View {
//Swipe to custom options ,by "Jack" this option not yet available in SwiftUI
let drag = DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onChanged {
if (self.offset.width > 0 ){ return }
self.offset.width = $0.translation.width
}.onEnded {
if $0.translation.width < -100 {
self.offset = .init(width: -100, height: 0)
} else {
self.offset = .zero
}
}
ZStack{
Rectangle().foregroundColor(.blue).offset(x: offset.width, y: offset.height)
.gesture(drag)
.animation(.easeIn, value: offset)
Text("test").foregroundColor(.white)
}.frame(minWidth: 0,
maxWidth: .infinity,
minHeight: 100,
maxHeight: .infinity,
alignment: .topLeading
)
}
}
struct cl_task_Previews: PreviewProvider {
static var previews: some View {
cl_task().previewLayout(.sizeThatFits)
}
}
List main view :
struct Item {
let uuid = UUID()
let value: String
}
struct w_tasks: View {
#State private var items = [Item]()
var body: some View {
ZStack {
List(self.items, id: \.uuid) {item in
cl_task()
}
.simultaneousGesture(DragGesture().onChanged({ value in
//Scrolled
}))
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
self.items.append(Item(value: "Item"))
}, label: {
Text("+")
.font(.system(size: 50))
.frame(width: 77, height: 70)
.foregroundColor(Color.white)
.padding(.bottom, 7)
})
.background(Color(hex : "#216D94"))
.cornerRadius(38.5)
.padding()
.shadow(color: Color.black.opacity(0.3),
radius: 3,
x: 3,
y: 3)
}
}
}
}
}
struct w_tasks_Previews: PreviewProvider {
static var previews: some View {
w_tasks()
}
}
I've posted my question after spending hours solving this issue as i am new to SwiftUI , any advice how to solve it ?
The solution is to give different distance for swipe, like below
struct cl_task: View {
#State private var offset: CGSize = .zero
var body: some View {
// give 25 distance makes vertical scroll enabled !!
let drag = DragGesture(minimumDistance: 25, coordinateSpace: .local)
.onChanged {
Tested with Xcode 12.4 / iOS 14.4

How to Save and Restore HSplitview Position in SwiftUI

I would like to be able to save and restore the position of a SwiftUI splitView but I can’t figure out how to do it. I haven’t found any examples and the documentation doesn’t have any info. I have the following:
struct ContentView: View {
var body: some View {
GeometryReader{geometry in
HSplitView(){
Rectangle().foregroundColor(.red).layoutPriority(1)
Rectangle().foregroundColor(.green).frame(minWidth:200, idealWidth: 200, maxWidth: .infinity)
}.frame(width: geometry.size.width, height: geometry.size.height)
}
}
}
Does anyone know how I can get the position of the slider so it can be saved, and also restored on startup?
Thanks!
Here's a workaround I've been using. It uses a plain HStack and a draggable view to recreate what HSplitView does. You can save then save the draggableWidth state however you want.
public struct SlideableDivider: View {
#Binding var dimension: Double
#State private var dimensionStart: Double?
public init(dimension: Binding<Double>) {
self._dimension = dimension
}
public var body: some View {
Rectangle().background(Color.gray).frame(width: 2)
.onHover { inside in
if inside {
NSCursor.resizeLeftRight.push()
} else {
NSCursor.pop()
}
}
.gesture(drag)
}
var drag: some Gesture {
DragGesture(minimumDistance: 10, coordinateSpace: CoordinateSpace.global)
.onChanged { val in
if dimensionStart == nil {
dimensionStart = dimension
}
let delta = val.location.x - val.startLocation.x
dimension = dimensionStart! + Double(delta)
}
.onEnded { val in
dimensionStart = nil
}
}
}
...
struct ContentView: View {
#AppStorage("ContentView.draggableWidth") var draggableWidth: Double = 185.0
var body: some View {
// This will be like an HSplitView
HStack(spacing: 0) {
Text("Panel 1")
.frame(width: CGFloat(draggableWidth))
.frame(maxHeight: .infinity)
.background(Color.blue.opacity(0.5))
SlideableDivider(dimension: $draggableWidth)
Text("Panel 2")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red.opacity(0.5))
}.frame(maxWidth: .infinity)
}
}