Sizing multiple vstack width in scroll view, SwiftUI - swift

I have a VStack:
VStack(alignment: .leading) {
Text(question)
.fontWeight(.heavy)
.font(.system(.footnote, design: .rounded))
.padding(.bottom)
Text(answer)
.fontWeight(.semibold)
.font(.system(.title, design: .rounded))
}
.padding(35)
.overlay(RoundedRectangle(cornerRadius: 12).stroke(Color("darkGrey"), lineWidth: 2))
.padding([.leading,.top,.trailing])
.frame(minWidth: UIScreen.main.bounds.width - 5,
minHeight: 50,
maxHeight: .infinity,
alignment: .topLeading
)
And Im using it in my View like:
ScrollView(.horizontal, showsIndicators: false) {
Group {
HStack {
questionCard(question: "Cats or Dogs", answer: "Dogs")
questionCard(question: "Cats or Dogs", answer: "Dogs")
}
}
}
This results in the following:
I'm trying to get the width of the box to the end of the screen (with .trailing space) and then when I scroll to the next, it should be the same width.

You could do something like the following:
struct ContentView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
Group {
HStack {
QuestionCard(question: "Cats or Dogs", answer: "Dogs")
QuestionCard(question: "Cats or Dogs", answer: "Dogs")
}
}
}
}
}
struct QuestionCard: View {
let question: String
let answer: String
var body: some View {
HStack {
Spacer()
VStack(alignment: .leading) {//<- Change the alignment if needed
Text(question)
.fontWeight(.heavy)
.font(.system(.footnote, design: .rounded))
.padding(.bottom)
Text(answer)
.fontWeight(.semibold)
.font(.system(.title, design: .rounded))
}
Spacer()
}
.padding(35)
.overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.black, lineWidth: 2))
.padding([.leading, .top, .trailing])
.frame(minWidth: UIScreen.main.bounds.width - 5,
minHeight: 50,
maxHeight: .infinity,
alignment: .top
)
}
}
So basically I`m just using an HStack and two Spacers in order to use all of the available space.
It looks like this:

Related

How do I Fix the alignment of this swiftUI view

I'm trying to put a number of DateCardViews inside a ScrollView as shown below
How do I fix the alignment DateCardView, so all DateCardViews are anchored to the top and start at the same level?
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top) {
ForEach(dates.prefix(8), id: \.id) { date in
DateCardView(meetDate: date)
}
}
.padding(.horizontal, 16.0)
}
.padding(.bottom, 20.0)
}
}
struct DateCardView: View {
#State var meetDate: MeetDate
#State var swap = false
var isExpired: Bool {
Date.isAboutToExpire(date: meetDate.date)
}
var body: some View {
VStack {
Image(swap ? meetDate.user.profileImages.first! : meetDate.bgIamge)
.resizable()
.cornerRadius(16)
.overlay(
Image((swap ? meetDate.bgIamge : meetDate.user.profileImages.first!))
.resizable()
.cornerRadius(6)
.frame(width: 32, height: 40)
.padding(.bottom, 8)
.padding(.trailing, 8)
.onTapGesture {
swap.toggle()
}, alignment: .bottomTrailing
)
.frame(height: 154)
VStack(alignment: .leading) {
HStack {
Text(meetDate.title)
.font(.custom("SFCompactText-Medium", size: 18))
.lineLimit(2)
}
HStack {
Text(Date.yearString(date: meetDate.date))
Text(Date.timeString(date: meetDate.date))
.foregroundColor(isExpired ? Color("Expired") : Color.black)
Spacer()
}.font(.custom("SFCompactText-Medium", size: 14))
HStack {
Text(meetDate.length)
.font(.custom("SFCompactText-Medium", size: 12))
Text(meetDate.cost)
.font(.custom("SFCompactText-Medium", size: 12))
.foregroundColor(Color("cost"))
}
}
}.frame(width: 138, height: 235)
}
}
You can probably fix this by adding a Spacer at the bottom of your outer VStack, but as the code in your question won't compile I can't test it,
VStack {
Image(swap ? meetDate.user.profileImages.first! : meetDate.bgIamge)
//
VStack(alignment: .leading) {
// etc
}
Spacer(minLength: 0)
}.frame(width: 138, height: 235)
You can add Spacer() in your Vstack. I think that will work or you can change your alingment values.
VStack(alignment: .leading) {
//your code
Spacer()
}

How to remove big blank space on my list pagination [SwiftUI]

I am new to SwiftUI and I trying to remove the blank space on my list pagination. Everytime when the list loaded the new page, a blank space is pop-up. how can I fix this?
You can see the problem by bellow attached image,
Screenshot
this is my list view
My List
List {
LazyVGrid(columns: setGridLayout(), spacing: 20) {
ForEach(viewModel.personPopularList, id: \.id) { person in
PeopleCardView(person: person)
.listRowBackground(Color.white)
.listRowSeparator(.hidden)
}
.id(UUID())
.frame(maxWidth: .infinity)
}
.listRowBackground(Color.white)
.listRowSeparator(.hidden)
}
.frame(maxWidth: .infinity)
.onAppear(perform: {
UITableView.appearance().contentInset.top = -20
UITableView.appearance().backgroundColor = UIColor.white
})
.listStyle(GroupedListStyle())
this is my cardview
My CardView
struct PeopleCardView: View {
#State var person: PersonPopularResult
var body: some View {
ZStack(alignment: .center) {
HStack(alignment: .center) {
WebImage(url: URL(string: Constant.POSTER_URL + (person.profilePath ?? "")))
.placeholder {
Image("placeholder")
}
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(RoundedRectangle(cornerRadius: 10))
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(Color.mPurple, lineWidth: 3))
Spacer()
VStack(alignment: .leading) {
Text("\(person.name!)")
.fontWeight(.bold)
.lineLimit(1)
.font(.system(size: 21))
.font(.headline)
Text("Popolarity Rate: \(String(format: "%.3f", person.popularity!))")
.fontWeight(.bold)
.foregroundColor(.mPurple)
.lineLimit(1)
.font(.system(size: 14))
.padding(.top, -8)
Spacer()
}
.padding([.top, .leading], 10)
Spacer()
}
.frame(width: 300, height: 100, alignment: .center)
.padding()
.background(
RoundedRectangle(cornerRadius: 15, style: .continuous)
.fill(.white)
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(Color.mPurple, lineWidth: 3))
.shadow(radius: 7)
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
thanks for anyone can help to my problem.

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"])
}
}

How to put an Image on top of a Color View in SwiftUI

I have an image that needs to be put in the top center of my view. How can I do so?
struct MyTextField: View
{
#ObservedObject var model: TextFieldModel
var body: some View
{
VStack(alignment: .leading, spacing: -60)
{
Color.black.position(CGPoint(x: 200, y: -50)).frame(width: 417, height: 120,
alignment: .top)
.background(Image(("appIconLogo")).resizable().frame(width: 50, height: 50))
//Spacer(minLength: 5)
VStack(alignment: .leading, spacing: 30)
{
Text("Welcome!")
.font(.system(size: 60, design: .rounded))
.foregroundColor(.black)
iTextField("Search Your Ticker", text: $model.text, isEditing: $model.isEditing)
.foregroundColor(.black)
.showsClearButton(true)
.onReturn
{
print($model.text)
NotificationCenter.default.post(name: Notification.Name(rawValue:
"isValidTicker"), object: nil)
}
.foregroundColor(.black)
.style(height: 58, font: nil, paddingLeading: 25, cornerRadius: 6,
hasShadow: true, image: Image(systemName: "magnifyingglass"))
.foregroundColor(.black)
}
}
.position(CGPoint(x: 200.0, y: 150.0))
.padding()
}
}
But my View looks like this. How can I move my image to the top center of the page where the black color is?
Here is a demo of possible layout. Prepared with Xcode 12.1 / iOS 14.1.
struct MyTextField: View
{
var body: some View
{
VStack {
Color.black
.frame(height: 120)
.overlay(Image(("plant")).resizable().frame(width: 50, height: 50))
.edgesIgnoringSafeArea(.top)
VStack(alignment: .leading, spacing: 30)
{
Text("Welcome!")
.font(.system(size: 60, design: .rounded))
.foregroundColor(.black)
.padding(.leading)
// .. other code
}.frame(maxWidth: .infinity, alignment: .leading)
}.frame(maxHeight: .infinity, alignment: .top)
}
}
It's a little confusing what you are trying to do in your code, but I think this might get you started. I made a background layer that extends to the edge of the screen, and then put a Content layer on top of it, where you can put the Image at the top of the VStack.
You should try to avoid setting exact width/height/CGPoints whenever possible in SwiftUI.
var body: some View {
ZStack {
// Background
Color.white
.edgesIgnoringSafeArea(.all)
// Content
VStack(spacing: 20) {
Image(systemName: "heart.fill") // Image here
Text("Welcome!") // Title
.font(.system(size: 60, design: .rounded))
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundColor(.black)
TextField("Search your ticker", text: $textFieldText) // Textfield
.frame(height: 50)
.background(Color.gray)
.cornerRadius(10)
Spacer()
}
.padding()
}
}

SwiftUI HStack with equal Height

I want the Text("111") to have the equal height of the VStack containing 2222... and 333....
struct Test7: View {
var body: some View
{ HStack (alignment: .top) {
Text( "111") // Shall have equal Height
.background(Color.red)
VStack(alignment: .leading){. // of this VStack
Text("2222222")
.background(Color.gray)
Text("333333333")
.background(Color.blue)
}
}
.background(Color.yellow)}
}
I tried with a GeometryReaderbut didn't get it to work
Here is possible approach using .alignmentGuide
struct Test7: View {
#State
private var height: CGFloat = .zero // < calculable height
var body: some View {
HStack (alignment: .top) {
Text( "111")
.frame(minHeight: height) // in Preview default is visible
.background(Color.red)
VStack(alignment: .leading) {
Text("2222222")
.background(Color.gray)
Text("333333333")
.background(Color.blue)
}
.alignmentGuide(.top, computeValue: { d in
DispatchQueue.main.async { // << dynamically detected - needs to be async !!
self.height = max(d.height, self.height)
}
return d[.top]
})
}
.background(Color.yellow)
}
}
Note: real result is visible only in LivePreview, because height is calculated dynamically and assign in next rendering cycle to avoid conflicts on #State.
use .frame(maxHeight: .infinity)
var body: some View {
HStack(alignment: .top) {
Text("111")
.frame(maxHeight: .infinity)
.background(Color.red)
VStack(alignment: .leading) {
Text("2222222")
.frame(maxHeight: .infinity)
.background(Color.gray)
Text("333333333")
.frame(maxHeight: .infinity)
.background(Color.blue)
}
}.background(Color.yellow)
.frame(height: 50)
}
result: demo