SwiftUI list row layout - swiftui

Back with a couple of SwiftUI layout questions :
I'm trying to display 2 lists side by side with custom cells.
I created the cell views (EventRow.swift) and I display them in my content view.
I added a border to my lists, for better visibility.
As you can see from the picture below, the result is ghastly:
I would like the gradient effect to be applied to the whole cell, width and height wise.
I tried setting the frame of my EventRow (using .infinity for width and height), but this crashes the app.
Since the size of EventRow is inferred, I also don't know how to adapt my row cells height to its size : you can see the horizontal delimitating bars are not fitted to my custom EventRow...
If anyone has some pointers for this, it would be greatly appreciated.
The sample project can be found here
But I also post my code below:
ContentView :
import SwiftUI
struct ContentView: View {
struct listsSetup: ViewModifier {
func body(content: Content) -> some View {
return content
.frame(maxHeight: UIScreen.main.bounds.size.height/3)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.blue, lineWidth: 1))
.padding([.top, .bottom])
}
}
var body: some View {
VStack {
HStack {
VStack { // 1 list Vstack
VStack {
Text("List 1")
.padding(.top)
List {
EventRow()
EventRow()
} // END of 1st List
}
.modifier(listsSetup())
} // END of 1st list VStack
VStack { // 2nd Vstack
VStack {
Text("List 2")
.padding(.top)
List {
EventRow()
EventRow()
} // END of Landings List
}
.modifier(listsSetup())
} // End of 2nd List VStack
} // End of 1st & 2nd lists HStack
.padding(.top)
Spacer()
} // END of VStack
} // END of body
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
EventRow :
import SwiftUI
struct EventRow: View {
var body: some View {
LinearGradient(gradient: Gradient(colors: [Color.white, Color.blue]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)
.overlay(
VStack{
HStack {
Text("Text one")
Spacer()
Text("Text two")
}
HStack {
Spacer()
Image(systemName: "flame")
.font(.body)
Spacer()
} // END of second HStack
.padding(.top, -14)
} //END of Vstack
)
}
}
struct EventRow_Previews: PreviewProvider {
static var previews: some View {
EventRow().previewLayout(.fixed(width: 300, height: 60))
}
}
Edit after trying Asperi's solution :
My actual EventRow code is as follows, and the listRowBackground modifier doesn't seem to have any effect :
import SwiftUI
import CoreData
struct EventRow: View {
var event: Events
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
// formatter.dateStyle = .long
formatter.dateFormat = "dd MMM yy"
return formatter
}
var body: some View {
VStack{
HStack {
Text(event.airportName ?? "")
.font(.headline)
Spacer()
Text(self.dateFormatter.string(from: event.eventDate!))
.font(.body)
}
HStack {
Text(event.flightNumber ?? "")
.font(.body)
Spacer()
if event.isSimulator {
Image(systemName: "s.circle")
.font(.body)
} else {
Image(systemName: "airplane")
.font(.body
)
}
Spacer()
if event.aircraftType == 0 {
Text("")
.font(.body)
} else if event.aircraftType == 1 {
Text("330")
.font(.body)
} else if event.aircraftType == 2 {
Text("350")
.font(.body)
}
} // END of second HStack
.padding(.top, -14)
} //END of Vstack
.listRowBackground(LinearGradient(gradient: Gradient(colors: [Color.white, Color.blue]), startPoint: .top, endPoint: .bottom))
}
}
struct EventRow_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newEvent = Events(context: context)
newEvent.eventDate = Date()
newEvent.aircraftType = 1
newEvent.airportName = "LDG tst"
newEvent.flightNumber = "AF TEST"
newEvent.id = UUID()
newEvent.isLanding = true
newEvent.isSimulator = false
return EventRow(event: newEvent).environment(\.managedObjectContext, context)
.previewLayout(.fixed(width: 300, height: 60))
}
}

Here is a solution to make gradient row-wide
struct EventRow: View {
var body: some View {
VStack{
HStack {
Text("Text one")
Spacer()
Text("Text two")
}
HStack {
Spacer()
Image(systemName: "flame")
.font(.body)
Spacer()
} // END of second HStack
.padding(.top, -14)
} //END of Vstack
.listRowBackground(LinearGradient(gradient: Gradient(colors: [Color.white, Color.blue]), startPoint: .top, endPoint: .bottom)
)
}
}

Related

Color behind the time on iOS

This is my code:
struct Account: View {
var body: some View {
VStack {
ScrollView {
HStack {
Text("Account")
.font(.largeTitle)
.fontWeight(.bold)
Spacer(minLength: 0)
}
.padding()
.background(Color.indigo)
VStack {
Text("Doe, John Jack")
.font(.title)
Divider()
.foregroundColor(Color.indigo)
HStack {
Text("")
}
}
Spacer(minLength: 0)
VStack {
Button(action: {
}) {
Text("Log Out")
.foregroundColor(.red)
.fontWeight(.bold)
}
}
}
}
}
}
If you run the code above, you will see that the indigo doesn't go behind the time and battery precentage. How can I make it do that?
Try like this:
struct Account: View {
var body: some View {
VStack {
ScrollView {
HStack {
Text("Account")
.font(.largeTitle)
.fontWeight(.bold)
Spacer(minLength: 0)
}
.padding()
.background(Color.indigo)
VStack {
Text("Doe, John Jack")
.font(.title)
Divider()
.foregroundColor(Color.indigo)
HStack {
Text("")
}
}
Spacer(minLength: 0)
VStack {
Button(action: {
}) {
Text("Log Out")
.foregroundColor(.red)
.fontWeight(.bold)
}
}
}.padding(.top, 66)
}
.background(Color.indigo)
.edgesIgnoringSafeArea(.all)
}
}
You would also have to add some top padding to the ScrollView since ignoring safe area is going to push all your views to the margins
You should ignore the top safe area for this:
.ignoresSafeArea(.container, edges: .top)
Full working example
struct ContentView: View {
var body: some View {
Color
.indigo
.ignoresSafeArea(.container, edges: .top)
}
}

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 :

Is there a way to keep a view always visible in ZStack in SwiftUI?

I have a view that I'd like to completely cover at some point and I'd like just one particular child view not to be covered. Is this possible in SwiftUI?
See this code for example:
import SwiftUI
#main
struct ZIndexExperimentApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
#State var showCover = false
var body: some View {
ZStack {
VStack {
Spacer()
Text("Normal text")
.font(.headline)
.padding()
Text("Text that should always be visible")
.font(.headline)
.padding()
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
if self.showCover {
VStack {
Rectangle()
.fill(Color.blue)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.edgesIgnoringSafeArea(.all)
}
}
.onAppear(perform: {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showCover = true
}
})
}
}
Is there a way to make the second Text to be on top of the cover? I tried to set the zindex on it to a high value but it didn't seem to have an effect.
I think using the foregroundColor or hidden is the better way, because if you kill some Views in your screen you would be notice some displacement on View which is not pleasant for user.
Version 1:
import SwiftUI
struct ContentView: View {
#State var showCover: Bool = Bool()
var body: some View {
ZStack {
if showCover { Color.blue }
VStack {
Spacer()
Text("Normal text")
.foregroundColor(showCover ? Color.clear : Color.primary)
.padding()
Text("Text that should always be visible")
.padding()
Spacer()
}
}
.font(.headline)
.ignoresSafeArea()
.onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { showCover = true } }
}
}
Version 2:
import SwiftUI
struct ContentView: View {
#State var showCover: Bool = Bool()
var body: some View {
ZStack {
if showCover { Color.blue }
VStack {
Spacer()
if showCover { Text("Normal text").padding().hidden() }
else { Text("Normal text").padding() }
Text("Text that should always be visible")
.padding()
Spacer()
}
}
.font(.headline)
.ignoresSafeArea()
.onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { showCover = true } }
}
}

List rows not centered

I am displaying some rows in a list (actually, 2 parallel lists in the example posted here), from a custom row view labeled EventRow.
In order to avoid bad UI on larger devices like an iPad, I limited the width of the EventRow to 200.
How could I get the EventRows to be centered in my lists on larger devices ?
I tried applying a .center alignment to the EventRows in the ForEach methods of my lists, tried doing the same on the lists as well, but nothing seems to work.
As an alternate solution, is there a way to set a MAX Spacer width ? I know you can set a minLength, but not a MAX it seems...
Here's a screenshot on the iPad Pro 11 sim :
The code for my EventRow file is as follows :
import SwiftUI
struct EventRow: View {
var body: some View {
VStack{
HStack {
Text("Text one")
Spacer()
Text("Text two")
}
HStack {
Spacer()
Image(systemName: "flame")
.font(.body)
Spacer()
} // END of second HStack
.padding(.top, -14)
} //END of Vstack
.frame(maxWidth: 200) // To limit width on larger devices
.listRowBackground(LinearGradient(gradient: Gradient(colors: [Color.white, Color.blue]), startPoint: .top, endPoint: .bottom))
}
}
struct EventRow_Previews: PreviewProvider {
static var previews: some View {
EventRow().previewLayout(.fixed(width: 300, height: 60))
}
}
And my ContentView :
struct ContentView: View {
struct listsSetup: ViewModifier {
func body(content: Content) -> some View {
return content
.frame(maxHeight: UIScreen.main.bounds.size.height/3)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.blue, lineWidth: 1))
.padding([.top, .bottom])
}
}
#State private var selected : Int = 0
var body: some View {
VStack {
HStack {
VStack { // 1 list Vstack
VStack {
Text("List 1")
.padding(.top)
List {
EventRow()
EventRow()
} // END of 1st List
}
.modifier(listsSetup())
} // END of 1st list VStack
VStack { // 2nd Vstack
VStack {
Text("List 2")
.padding(.top)
List {
EventRow()
EventRow()
} // END of Landings List
}
.modifier(listsSetup())
} // End of 2nd List VStack
} // End of 1st & 2nd lists HStack
.padding(.top)
Spacer()
Picker("", selection: $selected){
Text("0").tag(0)
Text("1").tag(1)
}.pickerStyle(SegmentedPickerStyle())
Text("\(selected)")
} // END of VStack
} // END of body
}
Again, any help would be appreciated.
Just embed it in one more container, like below (tested with Xcode 11.4)
VStack {
VStack{
HStack {
Text("Text one")
Spacer()
Text("Text two")
}
HStack {
Spacer()
Image(systemName: "flame")
.font(.body)
Spacer()
} // END of second HStack
.padding(.top, -14)
} //END of Vstack
.frame(maxWidth: 200) // To limit width on larger devices
}.frame(maxWidth: .infinity) // << here !!

How to remove List selection indicator and separator in SwiftUI?

I code a List in a ScrollView, when I selected a List cell to translate to another view and return back, the cell selected indicator did not disappear after selecting.
I hope after selected the list cell, the selected indicator should be disappear.
I debugged, I found that the ScrollView has some problems when it worked with List.If no ScrollView, the list selection behavior is all right, if plus the ScrollView outside the list, the problem become.
The other problem is How to remove the List Separator.
Thank you for your help!!!
#State var valueData: [String] = ["Apple", "Pear", "Orange", "Cake"]
var body: some View {
NavigationView {
ScrollView(.vertical) {
VStack(spacing: 10) {
DietListView(valueData: self.$valueData)
DietListView(valueData: self.$valueData)
.padding()
}
}
.frame(width: 352)
}
}
struct DietListView: View {
#Binding var valueData: [String]
var body: some View {
VStack {
List {
ForEach(self.valueData, id: \.self) { item in
NavigationLink(destination: DietItemDetailView()) {
HStack {
Text(item)
Spacer()
Text("100")
}
}
}
.onDelete { index in
self.valueData.remove(at: index.first!)
}
}
.frame(height: 300)
}
.frame(width: 352, height: 350)
.background(Color.white)
.cornerRadius(16)
.shadow(radius: 10)
}
}
the problem just like this:
At the moment (SwiftUI Beta 5) you can't customise List very much changing, for example, the divider style. What you can do, depending on your needs, is to use a ScrollView with ForEach and give the cell the style you want. For example:
struct ContentView: View {
#State var valueData: [String] = ["Apple", "Pear", "Orange", "Cake"]
var body: some View {
NavigationView {
ScrollView(.vertical) {
VStack(spacing: 10) {
DietListView(valueData: self.$valueData)
DietListView(valueData: self.$valueData)
.padding()
}
}
.frame(width: 352)
}
}
}
struct DietListView: View {
#Binding var valueData: [String]
var body: some View {
VStack {
ScrollView {
ForEach(self.valueData, id: \.self) { item in
NavigationLink(destination: Text("ciao")) {
HStack {
Text(item)
Spacer()
Text("100")
}
.foregroundColor(.primary)
.padding(10)
}
}
}
.frame(height: 300)
}
.frame(width: 352, height: 350)
.background(Color.white)
.cornerRadius(16)
.shadow(radius: 10)
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
Also, take a look at this: https://stackoverflow.com/a/56498261/1291872
EDIT: you can use onDelete, onMove and onInsert only within a List. If you want to let users delete a row in a ScrollView you must implement something yourself. Take a look at the code below for a simple (pretty ugly) example:
struct ContentView: View {
#State var valueData: [String] = ["Apple", "Pear", "Orange", "Cake"]
var body: some View {
NavigationView {
ScrollView(.vertical) {
VStack(spacing: 10) {
DietListView(valueData: self.$valueData)
DietListView(valueData: self.$valueData)
.padding()
}
}
.frame(width: 352)
}
}
}
struct DietListView: View {
#Binding var valueData: [String]
var body: some View {
VStack {
ScrollView {
ForEach(self.valueData.indices, id: \.self) { idx in
NavigationLink(destination: Text("ciao")) {
HStack {
Text(self.valueData[idx])
Spacer()
Text("100")
.padding(.trailing, 20)
Button(action: {
self.valueData.remove(at: idx)
}) {
Image(systemName: "xmark.circle")
.resizable()
.frame(width: 25, height: 25)
.foregroundColor(Color.red)
}
}
.foregroundColor(.primary)
.padding([.leading, .trailing], 20)
.padding([.top, .bottom], 10)
}
}
}
.frame(height: 300)
}
.frame(width: 352, height: 350)
.background(Color.white)
.cornerRadius(16)
.shadow(radius: 10)
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif