Filling HStack swiftUI - swift

I want to create a button stack like having a play and record button using SwiftUI, after creating it just does not look anything like what I wanted.
var body: some View {
HStack(alignment: /*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/, spacing: 8) {
Spacer()
Button(action: {
print("Recordinggg")
}, label: {
Text("Record")
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(40.0)
})
Spacer()
Button(action: {
print("Recordinggg")
}, label: {
Text("Play")
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(40.0)
})
Spacer()
}
}
What I actually want is something like this

Use proper frame, padding you can achieve this. Here is an example code.
Create ButtonStyle.
struct ThemeButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding([.top, .bottom], 10)
.foregroundColor(.white)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.background(Color.blue)
.cornerRadius(40.0)
}
}
Your view
struct ContentView: View {
#State private var phase: CGFloat = 0
var body: some View {
HStack(alignment: .center, spacing: 0) {
Button(action: {
print("Recordinggg")
}, label: {
Text("Record")
})
.buttonStyle(ThemeButtonStyle())
Spacer()
Button(action: {
print("Recordinggg")
}, label: {
Text("Play")
})
.buttonStyle(ThemeButtonStyle())
}
.padding()
}
}

Related

Can't display custom pop-up because my tab view is in NavigationView

I want to display a pop-up in my view, where I will be able to display a menu where I can choose how I fell, then it will show what I have chosen and close itself. If I am adding it to the view and it's presenting It shows wrong and Tab Bar does not disappear. Can someone provide a better way to show a pop-up over Tab Bar? The logic is something like this: button pressed -> shows pop-up -> choose status -> shows another pop-up -> disappears.
Code's provided below:
// Smile face that used in question
struct SmileFace: View {
var text: String
var image: String
#Binding var current: String
var body: some View {
Button {
withAnimation {
current = text
}
} label: {
VStack {
Image(image)
.resizable()
.scaledToFill()
.frame(width: 46, height: 46)
Text(text)
.foregroundColor(.white)
}
}
}
}
// Check in answer view
import SwiftUI
struct CheckInAskView: View {
let didClose: () -> Void
var didChose: Bool = false
#State var current: String
var emotions = [
"GREAT" : "good",
"GOOD" : "happy",
"OK" : "moderate",
"BAD" : "sad",
"TERRIBLE" : "verysad"
]
var body: some View {
VStack {
ZStack(alignment: .topLeading) {
Rectangle()
.fill(Color("navigation"))
.cornerRadius(15)
.frame(height: 601)
HStack(alignment: .top) {
ZStack(alignment: .top) {
Circle()
.fill(Color(red: 0.682, green: 0.384, blue: 0.486).opacity(0.10))
.frame(width: 173)
.offset(x: -173/2, y: -90/2)
.clipped()
}
Spacer()
Button {
didClose()
} label: {
ZStack {
Circle()
.fill(Color(red: 0.933, green: 0.933, blue: 0.933).opacity(0.30))
.frame(width: 24)
.clipped()
Image(systemName: "xmark")
.font(.system(size: 15))
.foregroundColor(Color(red: 0.762, green: 0.762, blue: 0.762))
}
.padding(10)
}
}
VStack(alignment: .center) {
Spacer()
Text("How do you feel now?")
.foregroundColor(.white)
.font(.custom("Manrope-Bold", size: 16))
HStack(spacing: 35) {
SmileFace(text: "GOOD", image: "good", current: $current)
}
.padding(.horizontal)
DoubleTextView(topText: "Recommendation for you", buttomText: "We have selected courses based on your goals and \nexperience", topTextSize: 16, buttomTextSize: 14)
BigFrameScrollViewHorizontal()
Spacer()
}
}
.frame(height: 601)
}
.frame(height: 601)
.transition(.move(edge: .bottom))
}
}
// View with all views
struct CheckInView: View {
#StateObject var sheetManager: SheetManager
var body: some View {
VStack {
HStack {
Text("How do you fell now?")
.foregroundColor(.white)
.font(.custom("Manrope-Bold", size: 16))
Spacer()
Button {
} label: {
ZStack {
HStack {
Text("Pass check in")
.padding([.top, .leading, .bottom])
.foregroundColor(.white)
.font(.custom("Manrope-Medium", size: 12))
Image(systemName: "chevron.right")
.foregroundColor(.white)
.font(.system(size: 15))
.padding(.trailing)
}
}
.background(Rectangle()
.fill(Color("active"))
.cornerRadius(100)
.frame(height: 26))
}
}
VStack {
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
}
HStack {
Button {
} label: {
ZStack {
Circle()
.fill(Color("navigation"))
.frame(width: 26)
Image(systemName: "chevron.left")
.foregroundColor(.white)
.font(.system(size: 14))
}
}
Button {
} label: {
ZStack {
Circle()
.fill(Color("navigation"))
.frame(width: 26)
Image(systemName: "chevron.right")
.foregroundColor(Color("inactive"))
.font(.system(size: 14))
}
}
}
.padding(.top)
}
.padding(.horizontal, 15.0)
}
}
struct CheckInView_Previews: PreviewProvider {
static var previews: some View {
CheckInView(sheetManager: SheetManager())
.background(.yellow)
}
}
If I have all of this, how can I create a pop-up over Tab View? Maybe a link to a similar problem?

Can't show dropdown menu over HStack in SwiftUI

I have a list item that needs to have a dropdown menu that shows on top of the other views in the HStack.
This is what I have currently:
struct ListRow: View {
#Binding var item: Item
#State var showDropdown: Bool = false
var body: some View {
ZStack {
HStack {
VStack {
Text(item.name)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .topLeading)
ProgressView(value: item.percentDone)
}.padding(.all, 10)
Button(action: {
self.showDropdown.toggle()
}, label: {
Image(systemName: "ellipsis.circle")
}).buttonStyle(BorderlessButtonStyle())
.overlay (
VStack {
if self.showDropdown {
Spacer(minLength: 40)
Text("TEST")
.onTapGesture {
print("Delete")
}
}
}.zIndex(10)
)
}
}
}
}
But when I run it and click the button this is what I see
It looks like the Text is not showing due to a view overflow/overlap with the rest of the HStack, but I thought that adding the .zIndex would place the dropdown on top of the rest of the views in the ZStack
Just set frame for your overlay view to make it exceed its main view 's size
.overlay (
VStack {
if self.showDropdown {
Spacer(minLength: 40)
Text("TEST")
.onTapGesture {
print("Delete")
}
}
}.frame(width: 100)
)
Or you can try another approach like ZStack or Menu (as you mentioned a better solution)
I figured out a better solution.
struct ListRow: View {
#Binding var item: Item
var body: some View {
HStack {
VStack {
Text(item.name)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .topLeading)
ProgressView(value: item.percentDone)
}.padding(.all, 10)
Menu {
Button("Delete", action: {
print("Delete")
})
} label: {
}
.menuStyle(BorderlessButtonMenuStyle())
.frame(width: 10, height: 10, alignment: .center)
}
}
}

How to do a "reveal"-style collapse/expand animation in SwiftUI?

I'd like to implement an animation in SwiftUI that "reveals" the content of a view to enable expand/collapse functionality. The content of the view I want to collapse and expand is complex: It's not just a simple box, but it's a view hierarchy of dynamic height and content, including images and text.
I've experimented with different options, but it hasn't resulted in the desired effect. Usually what happens is that when I "expand", the whole view was shown right away with 0% opacity, then gradually faded in, with the buttons under the expanded view moving down at the same time. That's what happened when I was using a conditional if statement that actually added and removed the view. So that makes sense.
I then experimented with using a frame modifier: .frame(maxHeight: isExpanded ? .infinity : 0). But that resulted in the contents of the view being "squished" instead of revealed.
I made a paper prototype of what I want:
Any ideas on how to achieve this?
Something like this might work. You can modify the height of what you want to disclose to be 0 when hidden or nil when not so that it'll go for the height defined by the views. Make sure to clip the view afterwards so the contents are not visible outside of the frame's height when not disclosed.
struct ContentView: View {
#State private var isDisclosed = false
var body: some View {
VStack {
Button("Expand") {
withAnimation {
isDisclosed.toggle()
}
}
.buttonStyle(.plain)
VStack {
GroupBox {
Text("Hi")
}
GroupBox {
Text("More details here")
}
}
.frame(height: isDisclosed ? nil : 0, alignment: .top)
.clipped()
HStack {
Text("Cancel")
Spacer()
Text("Book")
}
}
.frame(maxWidth: .infinity)
.background(.thinMaterial)
.padding()
}
}
No, this wasn't trying to match your design, either. This was just to provide a sample way of creating the animation.
Consider the utilization of DisclosureGroup. The following code should be a good approach to your idea.
struct ContentView: View {
var body: some View {
List(0...20, id: \.self) { idx in
DisclosureGroup {
HStack {
Image(systemName: "person.circle.fill")
VStack(alignment: .leading) {
Text("ABC")
Text("Test Test")
}
}
HStack {
Image(systemName: "globe")
VStack(alignment: .leading) {
Text("ABC")
Text("X Y Z")
}
}
HStack {
Image(systemName: "water.waves")
VStack(alignment: .leading) {
Text("Bla Bla")
Text("123")
}
}
HStack{
Button("Cancel", role: .destructive) {}
Spacer()
Button("Book") {}
}
} label: {
HStack {
Spacer()
Text("Expand")
}
}
}
}
The result looks like:
I coded this in under 5 minutes. So of course the design can be optimized to your demands, but the core should be understandable.
import SwiftUI
struct TaskViewCollapsible: View {
#State private var isDisclosed = false
let header: String = "Review Page"
let url: String
let tasks: [String]
var body: some View {
VStack {
HStack {
VStack(spacing: 5) {
Text(header)
.font(.system(size: 22, weight: .semibold))
.foregroundColor(.black)
.padding(.top, 10)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
Text(url)
.font(.system(size: 12, weight: .regular))
.foregroundColor(.black.opacity(0.4))
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
}
Spacer()
Image(systemName: self.isDisclosed ? "chevron.up" : "chevron.down")
.padding(.trailing)
.padding(.top, 10)
}
.onTapGesture {
withAnimation {
isDisclosed.toggle()
}
}
FetchTasks()
.padding(.horizontal, 20)
.padding(.bottom, 5)
.frame(height: isDisclosed ? nil : 0, alignment: .top)
.clipped()
}
.background(
RoundedRectangle(cornerRadius: 8)
.fill(.black.opacity(0.2))
)
.frame(maxWidth: .infinity)
.padding()
}
#ViewBuilder
func FetchTasks() -> some View {
ScrollView(.vertical, showsIndicators: true) {
VStack {
ForEach(0 ..< tasks.count, id: \.self) { value in
Text(tasks[value])
.font(.system(size: 16, weight: .regular))
.foregroundColor(.black)
.padding(.vertical, 0)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
.frame(maxHeight: CGFloat(tasks.count) * 20)
}
}
struct TaskViewCollapsible_Previews: PreviewProvider {
static var previews: some View {
TaskViewCollapsible(url: "trello.com", tasks: ["Hello", "Hello", "Hello"])
}
}

ScrollView + Custom View + ContextMenu animation glitch - SwiftUI

Is there a workaround to fix these animation glitches? Glitch video
The animation glitch on scroll
The one where the view disappears for less than a second
The view semantics is:
TabView {
NavigationView {
ScrollView {
VStack {
ForEach(){
MyCustomView()
.contextMenu()
MyCustomView is below, if anyone would want to test it:
struct CardVew: View {
var title: String
var description: String
var name: String
var task: String
var done: Bool
let tapVibration = UIImpactFeedbackGenerator(style: .light)
#State var details = false
var body: some View {
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 15)
.foregroundColor(Color("cardGray"))
.opacity(0.24)
VStack(alignment: .leading, spacing: .zero) {
titleBlock
descriptionBlock
bottomBlock
}
.padding([.leading, .trailing], 20)
.padding(.bottom, 15)
.padding(.top, 24)
}
.padding([.leading, .trailing], 12)
.sheet(isPresented: $details) {
CardSheetView(
title: title,
description: description,
task: task,
name: name
)
}
.onTapGesture {
tapVibration.impactOccurred()
details = true
}
.onAppear {
tapVibration.prepare()
}
}
private var titleBlock: some View {
HStack(alignment: .top) {
Text(title)
.font(.system(size: 22, weight: .bold))
.fixedSize(horizontal: false, vertical: true)
.frame(width: 244, alignment: .leading)
.padding(.bottom, 4)
if done {
Spacer()
Image("done")
.opacity(0.8)
}
}
}
private var bottomBlock: some View {
HStack(alignment: .bottom) {
HStack(alignment: .center) {
Image(systemName: "calendar")
Text("22.09")
}
Spacer()
Text(name)
.multilineTextAlignment(.trailing)
.opacity(0.6)
.font(.footnote)
.frame(width: 211, alignment: .trailing)
}
}
private var descriptionBlock: some View {
Text(description)
.opacity(0.8)
.fixedSize(horizontal: false, vertical: true)
.frame(width: 247, alignment: .leading)
.padding(.bottom, 38)
}
}
i tried to exclude all animations, sheet and anything that could cause such behaviour, but had no success

Collapse sidebar in SwiftUI (Xcode 12)

I'm trying to do a simple application in SwiftUI taking advantage of SwiftUI 2.0's new multiplatform project template, and I wish to add the option to collapse the sidebar as many other apps do.
I tried adding a boolean state variable that controls whether the sidebar should show or not, but that doesn't work because then the main view is turned translucent (I guess this is because macOS thinks the sidebar is now the main view).
Is there a way to natively achieve this in SwiftUI?
Please note I'm using macOS Big Sur, Xcode 12, and SwiftUI 2.0
Thanks in advance.
My code
ContentView.swift
import SwiftUI
struct ContentView: View {
#if os(iOS)
#Environment(\.horizontalSizeClass) private var horizontalSizeClass
#endif
#ViewBuilder var body: some View {
#if os(iOS)
if horizontalSizeClass == .compact {
TabController()
} else {
SidebarNavigation()
}
#else
SidebarNavigation()
.frame(minWidth: 900, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity)
#endif
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.sizeThatFits)
}
}
Sidebar.swift
import SwiftUI
struct SidebarNavigation: View {
enum HyperspaceViews {
case home
case localTimeline
case publicTimeline
case messages
case announcements
case community
case recommended
case profile
}
#State var selection: Set<HyperspaceViews> = [.home]
#State var searchText: String = ""
#State var showComposeTootView: Bool = false
#State var showNotifications: Bool = false
#State private var showCancelButton: Bool = false
var sidebar: some View {
VStack {
HStack {
TextField("Search...", text: $searchText)
.cornerRadius(4)
}
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
List(selection: self.$selection) {
Group {
NavigationLink(destination: Timeline().container.frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Home", systemImage: "house")
}
.accessibility(label: Text("Home"))
.tag(HyperspaceViews.home)
NavigationLink(destination: Text("Local").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Local", systemImage: "person.2")
}
.accessibility(label: Text("Local"))
.tag(HyperspaceViews.localTimeline)
NavigationLink(destination: Text("Public").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Public", systemImage: "globe")
}
.accessibility(label: Text("Public"))
.tag(HyperspaceViews.localTimeline)
NavigationLink(destination: Text("Messages").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Messages", systemImage: "bubble.right")
}
.accessibility(label: Text("Message"))
.tag(HyperspaceViews.localTimeline)
Divider()
NavigationLink(destination: Text("Announcements").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Announcements", systemImage: "megaphone")
}
.accessibility(label: Text("Announcements"))
.tag(HyperspaceViews.announcements)
NavigationLink(destination: Text("Community").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Community", systemImage: "flame")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.community)
NavigationLink(destination: Text("Recommended").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("Recommended", systemImage: "star")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.recommended)
Divider()
NavigationLink(destination: Text("Recommended").frame(maxWidth: .infinity, maxHeight: .infinity)) {
Label("hyperspacedev", systemImage: "tag")
}
.accessibility(label: Text("Community"))
.tag(HyperspaceViews.recommended)
}
}
.overlay(self.profileButton, alignment: .bottom)
.listStyle(SidebarListStyle())
}
}
var profileButton: some View {
VStack(alignment: .leading, spacing: 0) {
Divider()
NavigationLink(destination: ProfileView().container.frame(maxWidth: .infinity, maxHeight: .infinity)) {
HStack {
Image("amodrono")
.resizable()
.clipShape(Circle())
.frame(width: 25, height: 25)
Text("amodrono")
.font(.headline)
}
.contentShape(Rectangle())
}
.accessibility(label: Text("Your profile"))
.padding(.vertical, 8)
.padding(.horizontal, 16)
.buttonStyle(PlainButtonStyle())
}
.tag(HyperspaceViews.profile)
}
var body: some View {
NavigationView {
#if os(macOS)
sidebar.frame(minWidth: 100, idealWidth: 180, maxWidth: 200, maxHeight: .infinity)
#else
sidebar
#endif
Text("Content List")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.sheet(isPresented: self.$showComposeTootView) {
ComposeTootView(showComposeTootView: self.$showComposeTootView)
.frame(minWidth: 400, maxWidth: .infinity, minHeight: 200, maxHeight: .infinity)
}
.toolbar {
ToolbarItem {
Button(action: {
self.showNotifications.toggle()
}) {
Image(systemName: "bell")
}
.popover(
isPresented: self.$showNotifications,
arrowEdge: .bottom
) {
LazyVStack {
ForEach(0 ..< 10 ) { i in
Label("#\(i) liked your post!", systemImage: "hand.thumbsup")
.padding()
Divider()
}
}
}
}
ToolbarItem {
Button(action: {
self.showComposeTootView.toggle()
}) {
Image(systemName: "square.and.pencil")
}
}
}
}
}
struct SidebarNavigation_Previews: PreviewProvider {
static var previews: some View {
SidebarNavigation()
}
}
This worked for me -
https://developer.apple.com/forums/thread/651807
struct SwiftUIView: View {
var body: some View {
NavigationView{
}.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: toggleSidebar, label: {
Image(systemName: "sidebar.left")
})
}
}
}
}
func toggleSidebar() {
NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
It shows in the views on iOS so you will need some conditions for macOS only.
Apple provide NSToolbarToggleSidebarItemIdentifier which perform the toggleSidebar(_:) method.
.onAppear {
NSApp.keyWindow?.toolbar?.insertItem(withItemIdentifier: .toggleSidebar, at: 0)
}
This way will appear a button in your toolbar which action will invoke the sidebar toggle and it works perfectly.