ScrollView content not filling in SwiftUI - ios

I have a scrollview which content is a VStack containing a ForEach loop to create some Rows instead of a list. A List has some downsides like the dividers.
My Issue is that the Row is not filling the scrollview. I think the scrollview width is not filling the screen.
NavigationView {
Toggle(isOn: $onlineStatus) {
Text("Online Only")
}.padding([.leading, .trailing], 15)
ScrollView {
VStack(alignment: .trailing) {
ForEach(onlineStatus ? self.notes.filter { $0.dot == .green } : self.notes) { note in
NavigationButton(destination: Text("LOL")) {
CardRow(note: note)
.foregroundColor(.primary)
.cornerRadius(8)
.shadow(color: .gray, radius: 3, x: 0, y: -0.01)
}.padding([.leading, .trailing, .top], 5)
}.animation(self.onlineStatus ? .fluidSpring() : nil)
}
}.padding([.leading, .trailing])
.navigationBarTitle(Text("Your documents"))
}
This is giving me this result:
That's my CardRow:
struct CardRow: View {
var note: Note
var body: some View {
HStack {
Image(uiImage: UIImage(named: "writing.png")!)
.padding(.leading, 10)
VStack(alignment: .leading) {
Group {
Text(note.message)
.font(.headline)
Text(note.date)
.font(.subheadline)
}
.foregroundColor(.black)
}
Spacer()
VStack(alignment: .trailing) {
Circle().foregroundColor(note.dot)
.frame(width: 7, height: 7)
.shadow(radius: 1)
.padding(.trailing, 5)
Spacer()
}.padding(.top, 5)
}
.frame(height: 60)
.background(Color(red: 237/255, green: 239/255, blue: 241/255))
}
}

Use .frame(minWidth: 0, maxWidth: .infinity) on the RowView or inside of it

Best solution I found is to use GeometryReader to fill the ScrollView's contents to the outer view's width. And be sure to use a Spacer() in each row's HStack. This handles safe areas and rotation well.
struct Card : View {
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("Header")
.font(.headline)
Text("Description")
.font(.body)
}
Spacer()
}
.padding()
.background(Color.white)
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.15), radius: 8, x: 0, y: 0)
}
}
struct Home : View {
var body: some View {
GeometryReader { geometry in
NavigationView {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Card()
Card()
Card()
}
.padding()
.frame(width: geometry.size.width)
}
.navigationBarTitle(Text("Home"))
}
}
}
}
See resulting screenshot:

Try setting the frame width of the RowView to UIScreen.main.bounds.width:
.frame(width: UIScreen.main.bounds.width)

Related

Reload body items once data from service layer loads in swiftUI

I'm new to the swiftUI, looking for a way to refresh view once service data retrieved. What I want is, once page loads, -or before page loads- I want to call fillUI function so I can retrieve parsed json data from service layer, with that data I want to refresh this code block so my foreach block works with data I have:
VStack(spacing:15 ) {
ScrollView(.horizontal) {
VStack {
ForEach(0..<5) { i in
MeetingCellView(meetingData: meetingListData?.get(at: i) )
.frame(width: 340, height: 150)
.padding(.horizontal)
}.frame(width: 350)
}
}.frame(width: 350)
}
In UIKit, i was able to solve these issues with a way like loading and retrieving all the data first, then showing the view itself with a data. For swiftUI what is the best approach to do that?
Here is the full code of my related view body. I had searched internet but couldn't find the one yet.
import SwiftUI
struct HomeView: View {
#State var username: String = ""
#State var meetingCode: String = ""
#State var data: GetUserDetailModel? = nil
#State var meetingListData: [Datum]? = nil
#State var requestLoaded = false
var body: some View {
ZStack{
VStack {
Image("home.background")
.resizable()
.frame(maxHeight: 338)
Spacer()
ZStack {
VStack {
RoundedRectangle(cornerRadius: 8)
.padding(.top, -20)
.foregroundColor(.white)
}
ScrollView(.vertical, showsIndicators: false)
{
//MARK: - ScrollView Start
VStack {
HStack(spacing: 13.0) {
NavigationLink(destination: CreateMeetingView()) {
ZStack {
RoundedRectangle(cornerRadius: 12)
.foregroundColor(Color(red: 0.935, green: 0.914, blue: 0.957))
VStack(spacing: 18) {
HStack {
Image("icon.camera")
Spacer()
}
HStack {
Text("New Meeting")
.foregroundColor(Color(red: 0.476, green: 0.228, blue: 0.701))
.font(.custom("inter-semibold", size: 15))
Spacer()
}
}.padding(.horizontal, 15)
}.frame(maxWidth: .infinity, idealHeight: 101)
.padding(.leading, 25)
}
NavigationLink(destination: Text("there"))
{
ZStack {
RoundedRectangle(cornerRadius: 12)
.foregroundColor(Color(red: 0.897, green: 0.939, blue: 0.978))
VStack(spacing: 18) {
HStack {
Image("icon.calendar")
Spacer()
}
HStack {
Text("Schedule Now")
.foregroundColor(Color(red: 0.038, green: 0.525, blue: 0.917))
.font(.custom("inter-semibold", size: 15))
Spacer()
}
}.padding(.horizontal, 15)
}.frame(maxWidth: .infinity, idealHeight: 101)
.padding(.trailing, 25)
}
}
}
VStack {
HStack {
Text("Upcoming Meetings")
.font(.custom("inter-semibold", size: 17))
.padding(.leading, 25)
Spacer()
}
ZStack {
VStack(spacing: 30) {
HStack {
Image("upcoming.calendar")
}
HStack {
Text("You do not have a upcoming meeting.")
.font(.custom("inter-regular", size: 15))
.foregroundColor(Color(red: 0.692, green: 0.692, blue: 0.692))
}
}.hidden()
.padding(.vertical, 46)
VStack(spacing:15 ) {
ScrollView(.horizontal) {
VStack {
ForEach(0..<5) { i in
MeetingCellView(meetingData: meetingListData?.get(at: i) )
.frame(width: 340, height: 150)
.padding(.horizontal)
}.frame(width: 350)
}
}.frame(width: 350)
}
}
.padding(.horizontal ,15)
}.padding(.top, 25)
.padding(.bottom, 100)
//MARK: ScrollView End
}
}
}.ignoresSafeArea()
VStack {
HStack {
Image("splash.logo")
.resizable()
.frame(maxWidth: 100, maxHeight: 20)
.padding(.leading, 24)
Spacer()
Image("icon.profile")
.padding(.trailing,25)
}
VStack(spacing: 10.0) {
HStack {
Text("Good Morning,")
.font(.custom("inter-semibold", size: 13))
.foregroundColor(.white)
Spacer()
}
HStack {
Text(username)
.font(.custom("inter-semibold", size: 22))
.foregroundColor(.white)
Spacer()
}
}.padding(.leading, 24)
ZStack {
Color.white
VStack(spacing: 10.0) {
HStack {
Text("Join Meeting")
.font(.custom("inter-semibold", size: 13))
Spacer()
}
HStack {
TextField("Enter meeting code", text: $meetingCode)
.font(.custom("inter-regular", size: 15))
.keyboardType(.numbersAndPunctuation)
}
}.padding(.horizontal, 15)
}
.cornerRadius(6)
.frame(maxWidth: .infinity, maxHeight: 75.0)
.padding(.horizontal, 25.0)
.padding(.top, 30)
Spacer()
}.hiddenNavigationBarStyle()
}
.onAppear(perform: fillUI)
}
func fillUI() {
username = data?.givenName ?? "error"
Network.meetingList {meetings in
//print(meetings)
meetingListData = meetings?.data
requestLoaded = true
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
We use task(priority:_:) for that, .e.g
List {
ForEach(meetings) { meeting in
MeetingView(meeting: meeting)
}
}
.navigationTitle(loaded ? "Meetings" : "Loading...")
.task {
loaded = false
meetings = await Meeting.fetchAll()
loaded = true
}
Also your body is far too large and you have too many #State. Break it up into subviews and try to only have 1 or 2 #State per View.

SwiftUI simple view, need a push into right direction

I am complete beginner with SwiftUI and I can't wrap my head around how to connect these images with views that represents lines. Now I simply have 3 VStacks with image and text and put them into a HStack, but don't know how to connect these images with a line shown in red in the picture I attached. Note that there's some space between the line and the image. I need general direction and some hints, full working code not necessary.
Thank you.
How's this?
In SwiftUI, you use HStacks and VStacks to stack your Views. For the red line, a Rectangle should do. Here's the code:
struct ContentView: View {
var body: some View {
HStack { /// horizontal stack
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
Rectangle()
.fill(Color.red)
.frame(height: 5)
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
Rectangle()
.fill(Color.red)
.frame(height: 5)
VStack {
Image(systemName: "face.smiling")
.font(.system(size: 80))
.padding()
.border(Color.black, width: 5)
Text("Text TEXTEXT")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 800, height: 200))
}
}
Version 1.0.0
I decided to give my answer which is same like aheze answer with this difference that you can have CustomVerticalAlignment as well! As I see in your Image in question you want that also:
with CustomVerticalAlignment: In center!
without CustomVerticalAlignment: off center!
import SwiftUI
struct ContentView: View {
var body: some View {
HStack(alignment: .customVerticalAlignment) {
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
Capsule()
.fill(Color.red)
.frame(height: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
Capsule()
.fill(Color.red)
.frame(height: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
VStack {
Image(systemName: "star")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.padding()
.border(Color.black, width: 5)
.alignmentGuide(.customVerticalAlignment) { d in d[VerticalAlignment.center] }
Text("Text")
}
}
.padding()
}
}
extension VerticalAlignment {
struct CustomVerticalAlignment: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[VerticalAlignment.center]
}
}
static let customVerticalAlignment = VerticalAlignment(CustomVerticalAlignment.self)
}
Update Version 2.0.0
About this version: I would say it does the same job of version 1.0.0 in less code and also Text and Line are not depending on VStack or eachother any moere!
import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
image.overlay(text.offset(y: 40), alignment: .bottom)
capsule
image.overlay(text.offset(y: 40), alignment: .bottom)
capsule
image.overlay(text.offset(y: 40), alignment: .bottom)
}
.padding(50)
}
var image: some View {
return Image(systemName: "star.fill")
.resizable()
.scaledToFit()
.padding(10)
.shadow(radius: 10)
.frame(width: 50, height: 50, alignment: .center)
.foregroundColor(Color.red)
.background(Color.yellow)
.border(Color.black, width: 5)
}
var capsule: some View {
return Capsule()
.fill(Color.red)
.frame(height: 5)
}
var text: some View {
return Text("Hello World!")
.lineLimit(1)
.fixedSize()
}
}
You could define a Shape that represents your line.
I used the spacing parameter of HStack to do the spacing:
struct MyLine : Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 0, y: rect.midY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
}
}
}
struct ContentView: View {
var body: some View {
HStack(spacing: 10) {
VStack {
Image(systemName: "pencil")
Text("Label")
}
MyLine().stroke(Color.red)
VStack {
Image(systemName: "pencil")
Text("Label 2")
}
MyLine().stroke(Color.red)
VStack {
Image(systemName: "pencil")
Text("Label 3")
}
}
}
}
You could add a lineWidth parameter to make the stroke thicker:
.stroke(Color.red, lineWidth: 4)
Also, if you didn't using spacing on the HStack, you could using a padding modifier on either the VStacks or the MyLines to get the spacing.

Injecting A Button to ScrollView

I'm developing a iOS app relies on SwiftUI.
I have a ZStack view and inside it, I call a another view along with a button.
ZStack(alignment: .bottomTrailing) {
ImageStepView(data: self.data[randomImageNum])
Button(action: { self.showFavorites = true }) {
HStack {
Image(systemName: "suit.heart.fill")
Text("FAVORITES")
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 15)
.foregroundColor(.white)
.padding()
.background(Color.black.opacity(0.6))
.cornerRadius(5)
.padding(.horizontal, 20)
}
}
ImageStepView.swift
struct ImageStepView: View {
var data: ImageDataModel
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
VStack{
Image(data.image)
.resizable()
.border(Color.white, width: 5)
.overlay(
Rectangle().stroke(Color.white, lineWidth: 4))
.shadow(color: Color.gray, radius: 10, x: 10, y: 10)
.scaledToFit()
.frame(height: geometry.size.height-110)
} .padding()
VStack{
VStack(alignment: .leading) {
HStack{...}
HStack {...}
}
Spacer()
.frame(height: 50)
VStack(alignment: .leading){
VStack{
HStack {...}
HStack {...}
HStack {...}
}
}
}.padding()
}.background(Color("Color").ignoresSafeArea(.all))
.frame(width: geometry.size.width)
.frame(minHeight: geometry.size.height)
}
}
}
ImageStepView has a ScroolView, that's why Button not appears on the end of ScroolView, it appears on bottom of the screen.
What I want is to show The Button not on bottom of the screen but end of the ImageStepView.
You can make the ImageStepView accept a generic parameter - a view to be injected:
struct ImageStepView<Injected: View>: View {
var data: ImageDataModel
var injectedView: () -> Injected
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
// ScrollView contents
injectedView()
}
.background(Color("Color").ignoresSafeArea(.all))
.frame(width: geometry.size.width)
.frame(minHeight: geometry.size.height)
}
}
}
and pass the injected view to the ImageStepView:
ImageStepView(data: self.data[randomImageNum]) {
Button(action: { self.showFavorites = true }) { ... }
}
or
ImageStepView(data: self.data[randomImageNum]) { EmptyView() }

Shadows clipped by ScrollView

Is there a way I can get shadows applied to an image to also show outside of the parent view? Below you can see a sample, where I list out some images in a ScrollView and HStack. The image/artwork has a shadow applied to it, but this gets clipped by the ScrollView.
Screenshot for reference:
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in
NavigationLink(destination: StationDetailView(station: item)) {
VStack(alignment: .leading) {
if item.artwork != nil {
KFImage(self.artworkURLForStation(item)!)
.resizable()
.frame(width: 130, height: 130)
.scaledToFit()
.cornerRadius(6)
.shadow(radius: 5)
} else {
RoundedRectangle(cornerRadius: 6)
.background(Color.purple)
.shadow(radius: 5)
}
Text(item.name)
.font(.callout)
.foregroundColor(.primary)
Text(item.categories.first?.name ?? "N/A")
.font(.callout)
.foregroundColor(.secondary)
}
.frame(minWidth: 0, maxWidth: 130, alignment: .leading)
}
.buttonStyle(PlainButtonStyle())
}
}
}
To make shadow uncut, add padding to HStack
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in
// ... other code
}.padding() // << here !!
}
I've found a decent workaround for this problem.
This is image BEFORE
This is image AFTER
I've added 2 paddings to ScrollView and to content of ScrollView with the same amount of padding but one with NEGATIVE value like this:
struct ScrollViewClippingProblem: View {
var body: some View {
VStack {
Text("Lorem Ipsum")
.font(.title)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top) {
ForEach(0..<10, content: { item in
Text("\(item)")
.font(.title)
.padding()
.background(Circle().fill(.red))
.shadow(color: .blue, radius: 10, x: 15, y: 10)
})
}
.padding(.vertical, 40) // <- add padding here to make the space for the shadow
}
.padding(.vertical, -40) // <- add NEGATIVE padding here of the same value to shrink the space you created with the padding above
Text("Lorem Ipsum")
.font(.title)
}
.background(.ultraThinMaterial)
}}
I hope this helps somebody! :)
There's a much simpler solution to this, provided that the shadows are uniform for each element within the HStack:
Just add the .shadow modifier to the ScrollView rather than to the element itself.
Using #Hollycene's answer for context.
See SwiftUI Preview Image
struct ScrollViewClippingSolutionView: View {
var body: some View {
VStack {
Divider().padding()
Text("Shadow on Element")
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top) {
ForEach(0..<10) { item in
Text("\(item)")
.font(.title)
.padding()
.background(Circle().fill(.red))
.shadow(color: .blue, radius: 10, x: 15, y: 10) // <- Don't place .shadow modifier here
}
}
}
Divider().padding()
Text("Shadow on ScrollView")
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top) {
ForEach(0..<10) { item in
Text("\(item)")
.font(.title)
.padding()
.background(Circle().fill(.red))
}
}
}
.shadow(color: .blue, radius: 10, x: 15, y: 10) // <- Place .shadow modifier here instead
Divider().padding()
}
}
}

How to create View inside another view with SwiftUI?

I need to make such a simple thing, but can't figure out how.
So I need to create a View which I already have inside another view. Here how it looks like now ↓
Here's my button:
struct CircleButton: View {
var body: some View {
Button(action: {
self
}, label: {
Text("+")
.font(.system(size: 42))
.frame(width: 57, height: 50)
.foregroundColor(Color.white)
.padding(.bottom, 7)
})
.background(Color(#colorLiteral(red: 0.4509803922, green: 0.8, blue: 0.5490196078, alpha: 1)))
.cornerRadius(50)
.padding()
.shadow(color: Color.black.opacity(0.15),
radius: 3,
x: 0,
y: 4)
}
}
Here's a view which I want to place when I tap the button ↓
struct IssueCardView: View {
var body: some View {
ZStack (alignment: .leading) {
Rectangle()
.fill(Color.white)
.frame(height: 50)
.shadow(color: .black, radius: 20, x: 0, y: 4)
.cornerRadius(8)
VStack (alignment: .leading) {
Rectangle()
.fill(Color(#colorLiteral(red: 0.6550863981, green: 0.8339114785, blue: 0.7129291892, alpha: 1)))
.frame(width: 30, height: 8)
.cornerRadius(8)
.padding(.horizontal, 10)
Text("Some text on card here")
.foregroundColor(Color(UIColor.dark.main))
.font(.system(size: 14))
.fontWeight(.regular)
.padding(.horizontal, 10)
}
}
}
}
Here's a view where I want to place this IssueCardView ↓. Instead of doing it manually like now I want to generate this View with button.
struct TaskListView: View {
var body: some View {
ScrollView(.vertical, showsIndicators: false, content: {
VStack (alignment: .leading, spacing: 8) {
**IssueCardView()
IssueCardView()
IssueCardView()
IssueCardView()
IssueCardView()**
}
.frame(minWidth: 320, maxWidth: 500, minHeight: 500, maxHeight: .infinity, alignment: .topLeading)
.padding(.horizontal, 0)
})
}
}
Although it works with scrollView and stack, You should use a List for these kind of UI issues (as you already mentioned in the name of TaskListView)
struct TaskListView: View {
typealias Issue = String // This is temporary, because I didn't have the original `Issue` type
#State var issues: [Issue] = ["Some issue", "Some issue"]
var body: some View {
ZStack {
List(issues, id: \.self) { issue in
IssueCardView()
}
CircleButton {
self.issues += ["new issue"]
}
}
}
}
I have added let action: ()->() to CircleButton. So I can pass the action to it.

Resources