Swift UI Remove Extra List Empty Cells without Navigation Controller - ios

Swift UI - Xcode
Problem: I have extra cells when my list is initialized. However, unlike other posts I do not have a navigation view. Is it mandatory to have a NavigationView in order to remove the extra cells from my list.
I have tried to implement a Navigation View but im not sure if its mandatory and how to properly implement.
.navigationBarTitle("List")
.listStyle(GroupedListStyle())
I would like to start a new Text or UIButton directly below the last "Current" cell without extra white spaces.
var body: some View {
VStack(alignment: .leading) {
Image("covidImage")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(5)
Text("COVID DATA")
.font(.system(.title, design: .rounded))
.bold()
.lineLimit(3)
.padding(.bottom, 3)
.padding(.leading, 10)
Text("Represented by Sate in the United States")
.font(.subheadline)
.foregroundColor(.secondary)
.padding(.leading, 10)
.padding(.bottom, 0)
Text("Current State: CA")
.font(.subheadline)
.foregroundColor(.secondary)
.padding(.leading, 10)
.padding(.bottom, 10)
//List to Initialize TableView Data
List(covid) { covidData in
Image(systemName: "photo")
.padding()
HStack {
Text(covidData.dataTitle).frame(maxWidth: .infinity, alignment: .leading)
Text(covidData.dataValue)
.font(.subheadline)
.frame(maxWidth: .infinity, alignment: .trailing)
//.color(.gray)
}
}//END List
}//END Original VStack
}//END Some View

They are not empty cells. The List just fills all available space and draws empty rows placeholders where there is no content. In your scenario is needed to limit height of List to its content.
Here is a solution. Tested with Xcode 11.4 / iOS 13.4
For better visibility let's separate your list into own view named CovidDataList, then here is in your provided body:
//List to Initialize TableView Data
CovidDataList(covid: self.covid)
}//END List
Note1: The height of list updated in run-time so should be tested in running application (not in Preview)
Note2: I tested with replicated cover data model so some adapting might be needed to your code
struct CovidDataList: View {
#Environment(\.defaultMinListRowHeight) var minRowHeight
let covid: [CovidData]
#State private var listHeight = CGFloat.infinity
var body: some View {
List {
ForEach(covid, id: \.self) { covidData in
HStack {
Image(systemName: "photo")
.padding()
HStack {
Text("Title").frame(maxWidth: .infinity, alignment: .leading)
Text("Value")
.font(.subheadline)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.listRowInsets(EdgeInsets()).padding(.horizontal)
}
.anchorPreference(key: BoundsPreferenceKey.self, value: .bounds) { [$0] }
}
.backgroundPreferenceValue(BoundsPreferenceKey.self) { rects in
GeometryReader { gp in
self.updateListFrame(gp: gp, anchors: rects)
}
}.frame(maxHeight: listHeight)
}
private func updateListFrame(gp: GeometryProxy, anchors: [Anchor<CGRect>]) -> some View {
let contentHeight = anchors.reduce(CGFloat.zero) { $0 + gp[$1].size.height }
DispatchQueue.main.async { // << required !!
self.listHeight = max(contentHeight, self.minRowHeight * CGFloat(self.covid.count))
}
return Color.clear
}
}
Note: BoundsPreferenceKey is taken from this my answer

Related

Need to create a chat bubble like Whatsapp with two labels on top of the message in SwiftUI

I'm trying to create a chat bubble like this:
Actual Bubble
Actual Bubble 2.0
This is what I have been able to achieve so far.
My attempt
My attempt
This is my code so far:
import SwiftUI
struct TestingView: View {
var body: some View {
ZStack {
/// header
VStack(alignment: .trailing) {
HStack {
HStack() {
Text("abcd")
}
HStack {
Text("~abcd")
}
}.padding([.trailing, .leading], 15)
.fixedSize(horizontal: false, vertical: true)
/// text
HStack {
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
}.padding([.leading, .trailing], 15)
/// timestamp
HStack(alignment: .center) {
Text("12:00 PM")
}.padding(.trailing,15)
}.background(Color.gray)
.padding(.leading, 15)
.frame(maxWidth: 250, alignment: .leading)
}
}
}
struct TestingView_Previews: PreviewProvider {
static var previews: some View {
TestingView()
}
}
The main goal is that I want the two labels on top to be distant relative to the size of the message content. I am not able to separate the two labels far apart i.e one should be on the leading edge of the bubble and the other one on the trailing edge.
Already tried spacer, it pushes them to the very edge, we need to apart them relative to the content size of the message as shown in attached images.
Here is a simplified code.
Regarding Spacer: To achieve your desired result you put both Text views inside of a HStack, and put a Spacer between them. So the Spacer pushes them apart to the leading and trailing edge.
Also I recommend to only use one padding on the surrounding stack.
VStack(alignment: .leading) {
// header
HStack {
Text("+123456")
.bold()
Spacer() // Spacer here!
Text("~abcd")
}
.foregroundStyle(.secondary)
// text
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
.padding(.vertical, 5)
// timestamp
Text("12:00 PM")
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding()
.background(Color.gray.opacity(0.5))
.cornerRadius(16)
.frame(maxWidth: 250, alignment: .leading)
}
We can put that header into overlay of main text, so it will be always aligned by size of related view, and then it is safe to add spacer, `cause it do not push label wider than main text.
Tested with Xcode 13.4 / iOS 15.5
var body: some View {
let padding: CGFloat = 15
ZStack {
/// header
VStack(alignment: .trailing) {
/// text
HStack {
//Text("Hello Everyone") // short test
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!") // long test
}
.padding(.top, padding * 2)
.overlay(
HStack { // << here !!
HStack() {
Text("abcd")
}
Spacer()
HStack {
Text("~abcd")
}
}
, alignment: .top)
.padding([.trailing, .leading], padding)
/// timestamp
HStack(alignment: .center) {
Text("12:00 PM")
}.padding(.trailing, padding)
}.background(Color.gray)
.padding(.leading, padding)
.frame(maxWidth: 250, alignment: .leading)
}
}
To separate two components with fairly space in the middle, use HStack{} with Spacer().
This is a sample approach for this case. Code is below the image:
VStack {
HStack {
Text("+92 301 8226")
.foregroundColor(.red)
Spacer()
Text("~Usman")
.foregroundColor(.gray)
}
.padding(.bottom, 5)
.padding(.horizontal, 5)
Text("Testing testingtesting testing testing testingtesting testing testing testing testing testing testing testing testing testing.")
.padding(.horizontal, 5)
HStack {
Spacer()
Text("2:57 AM")
.foregroundColor(.gray)
.font(.subheadline)
}
.padding(.trailing, 5)
}
.frame(width: 300, height: 160)
.background(.white)
.cornerRadius(15)

How to adjust navigationBarTitle and Label Text alignment in SwiftUI

I just learned swiftUI and I got little trouble. I want to make navigationBarTitle and title headline alignment like this:
Image 1: I want to make my view like this
I have tried to make like below but it does not work:
struct HeaderView: View {
var body: some View {
NavigationView {
VStack {
Image("kante_training_champions_league")
.resizable()
.scaledToFill()
.frame(width: 370, height: 150)
.cornerRadius(10.0)
Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
.font(.title)
.fontWeight(.bold)
.multilineTextAlignment(.leading)
.frame(width: 370)
Spacer()
}
.navigationBarTitle("Chelsea FC")
}
}
}
From my code above, I got a view like this:
Image 2: I got a view like this from my code above
Could someone help me how to get a view like I want
Try leading alignment
var body: some View {
NavigationView {
VStack(alignment: .leading) { // << here !!
// ... no changes in image
Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
.font(.title)
.fontWeight(.bold)
.padding(.leading) // << here !!
.multilineTextAlignment(.leading)
}
You should add alignment to StackView. You can change alignment to .leading, .trailing or .center. It is centered by default thats why you are having the label in center.
var body: some View {
NavigationView {
VStack(alignment: .leading) {
// Your Code
}
}
}
Remove .frame(width: 370) and use .frame(maxWidth: .infinity) so that the text takes the whole width of its parent.
VStack {
Image("kante_training_champions_league")
.resizable()
.scaledToFill()
.frame(width: 370, height: 150)
.cornerRadius(10.0)
Text("KANTE: NEW PLAYERS DON’T SEEM NEW")
.font(.title)
.fontWeight(.bold)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity)
Spacer()
}

Applying resizable() on an Image affects text in SwiftUI

I am working on SwiftUI to make a widget and I can't figure out if I'm doing something wrong or there's a bug in SwiftUI.
I have an Image that I use as a background and at the top there's a text. If I apply resizable() to the Image it also affects the behaviour of the text.
var body: some View {
ZStack {
VStack {
Image(affirmation.customImageName ?? "c_0")
.resizable()
.scaledToFill()
.clipped()
}
HStack {
Text(affirmation.title)
.font(.body)
.multilineTextAlignment(.leading)
.lineLimit(nil)
Spacer()
}
.padding(.leading, 5)
.padding(.top, 5)
}
}
Creates this view:
While this code:
var body: some View {
ZStack {
VStack {
Image(affirmation.customImageName ?? "c_0")
.scaledToFill()
.clipped()
}
HStack {
Text(affirmation.title)
.font(.body)
.multilineTextAlignment(.leading)
.lineLimit(nil)
Spacer()
}
.padding(.leading, 5)
.padding(.top, 5)
}
}
Creates this view:

Automatically adjustable view height based on text height in SwiftUI

I am trying to create a view in SwiftUI where the background of the image on the left should scale vertically based on the height of the text on the right.
I tried a lot of different approaches, from GeometryReader to .layoutPriority(), but I haven't managed to get any of them to work.
Current state:
Desired state:
I know that I could imitate the functionality by hardcoding the .frame(100) for the example I posted, but as text on the right is dynamic, that wouldn't work.
This is full code for the view in the screenshot:
import SwiftUI
struct DynamicallyScalingView: View {
var body: some View {
HStack(spacing: 20) {
Image(systemName: "snow")
.font(.system(size: 32))
.padding(20)
.background(Color.red.opacity(0.4))
.cornerRadius(8)
VStack(alignment: .leading, spacing: 8) {
Text("My Title")
.foregroundColor(.white)
.font(.system(size: 13))
.padding(5)
.background(Color.black)
.cornerRadius(8)
Text("Dynamic text that can be of different leghts. Spanning from one to multiple lines. When it's multiple lines, the background on the left should scale vertically")
.font(.system(size: 13))
}
}
.padding(.horizontal)
}
}
struct DailyFactView_Previews: PreviewProvider {
static var previews: some View {
DynamicallyScalingView()
}
}
Here is a solution based on view preference key. Tested with Xcode 11.4 / iOS 13.4
struct DynamicallyScalingView: View {
#State private var labelHeight = CGFloat.zero // << here !!
var body: some View {
HStack(spacing: 20) {
Image(systemName: "snow")
.font(.system(size: 32))
.padding(20)
.frame(minHeight: labelHeight) // << here !!
.background(Color.red.opacity(0.4))
.cornerRadius(8)
VStack(alignment: .leading, spacing: 8) {
Text("My Title")
.foregroundColor(.white)
.font(.system(size: 13))
.padding(5)
.background(Color.black)
.cornerRadius(8)
Text("Dynamic text that can be of different leghts. Spanning from one to multiple lines. When it's multiple lines, the background on the left should scale vertically")
.font(.system(size: 13))
}
.background(GeometryReader { // << set right side height
Color.clear.preference(key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height)
})
}
.onPreferenceChange(ViewHeightKey.self) { // << read right side height
self.labelHeight = $0 // << here !!
}
.padding(.horizontal)
}
}
struct ViewHeightKey: PreferenceKey {
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = value + nextValue()
}
}
This is the answer without workaround.
struct DynamicallyScalingView: View {
var body: some View {
HStack(spacing: 20) {
Image(systemName: "snow")
.frame(maxHeight: .infinity) // Add this
.font(.system(size: 32))
.padding(20)
.background(Color.red.opacity(0.4))
.cornerRadius(8)
VStack(alignment: .leading, spacing: 8) {
Text("My Title")
.foregroundColor(.white)
.font(.system(size: 13))
.padding(5)
.background(Color.black)
.cornerRadius(8)
Text("Dynamic text that can be of different leghts. Spanning from one to multiple lines. When it's multiple lines, the background on the left should scale vertically")
.font(.system(size: 13))
}
.frame(maxHeight: .infinity) // Add this
}
.padding(.horizontal)
.fixedSize(horizontal: false, vertical: true) // Add this
}
}

SwiftUI - List scrolling underneath status bar text

I Create List and add VStack inside and added some views inside VStack. When I run the project, I observer scrolling of List going beyond the safe area. FYI if I remove Frame property still same result.Simulator gif
struct ContentView : View {
var body: some View {
List(0..<5) { item in
HStack(alignment: VerticalAlignment.top, spacing: 5) {
Image(systemName: "photo")
VStack(alignment: HorizontalAlignment.leading, spacing: 10) {
Text("USA")
.font(.headline)
Text("This is an extremely long string that will never fit even the widest of Phones Excerpt From: Paul Hudson. “SwiftUI by Example”. Apple Books. ")
.lineLimit(nil)
.font(.subheadline)
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.red)
.onAppear() {
print("on Appear")
}.onDisappear() {
print("on Disappear")
}
}
}
Inspired by Shauket Sheikh. You can directly add the .padding(.top) to the List and it's done. No need for a VStack.
struct ContentView : View {
var body: some View {
List(0..<5) { item in
HStack(alignment: VerticalAlignment.top, spacing: 5) {
Image(systemName: "photo")
VStack(alignment: HorizontalAlignment.leading, spacing: 10) {
Text("USA")
.font(.headline)
Text("This is an extremely long string that will never fit even the widest of Phones Excerpt From: Paul Hudson. “SwiftUI by Example”. Apple Books. ")
.lineLimit(nil)
.font(.subheadline)
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.red)
.onAppear() {
print("on Appear")
}.onDisappear() {
print("on Disappear")
}
.padding(.top)
}
}
I had the same problem with my ScrollView
My solution was simpler than the rest, so give this a shot:
Just add .clipped() modifier to your List or ScrollView and this should prevent your content from scrolling out of its bounds.
And you can then combine this with edgesIgnoringSafeArea(.bottom) if you want your content to still scroll off screen from the bottom. But watch out - edgesIgnoringSafeArea(.bottom) has to come after .clipped() if you want this effect.
You can also use VStack and set .padding() of it.
Code :
struct ContentView : View {
var body: some View {
VStack {
List(0..<5) { item in
HStack(alignment: VerticalAlignment.top, spacing: 5) {
Image(systemName: "photo")
VStack(alignment: HorizontalAlignment.leading, spacing: 10) {
Text("USA")
.font(.headline)
Text("This is an extremely long string that will never fit even the widest of Phones Excerpt From: Paul Hudson. “SwiftUI by Example”. Apple Books. ")
.lineLimit(nil)
.font(.subheadline)
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.red)
.onAppear() {
print("on Appear")
}.onDisappear() {
print("on Disappear")
}
}.padding()
}
}

Resources