How can I change DatePicker font weight in SwiftUI - swift

I've tried below code. But .font function does not change anything. I want to the date more darker. How can I do that?
struct TestView: View {
#State private var date = Date()
var body: some View {
HStack {
DatePicker("", selection: $date, in: ...Date(), displayedComponents: .date)
.padding()
.labelsHidden()
.accentColor(.red)
.font(Font.body.weight(.bold))
Spacer()
}
}
}

While you can't specifically change the text for the DatePicker, you can use and HStack to accomplish the desired outcome.
HStack {
Text("End Date")
.font(.custom((Fonts.gse), size: 18))
.fontWeight(.medium)
Spacer()
DatePicker("", selection: self.$endingDate, in: self.dateRange, displayedComponents: [.date, .hourAndMinute])
}

Related

Keyboard pushing up buttons in Stack

How do I add a scrollView without covering everything else up. I added .ignoresSafeArea(.keyboard) to the outer Stack to stop the keyboard from pushing my buttons at the bottom up but when I try to add a scrollView all that is displayed is the confirm and back buttons and navigation title and none of the form I want the user to scroll through and fill out
import SwiftUI
struct NewEventView: View{
#State private var newEventName: String = ""
#State private var newEventAddress: String = ""
#State private var newEventPrivacy: String = ""
#State private var newEventMaxAttendents: String = ""
#State private var newEventPrice: String = ""
#State private var newEventNotes: String = ""
#State private var newEventStartTime = Date.now
#State private var newEventEndTime = Date()
#State private var newEventStartDate = Date.now
#State private var newEventEndDate = Date()
#State private var newEventType: String = ""
var body: some View{
VStack{
Text("New Event")
List(){
HStack{
Text("Event Name: ")
TextField("Name", text: $newEventName)
}
HStack{
Text("Address: ")
TextField("Address", text: $newEventAddress)
}
HStack{
Picker(selection: $newEventPrivacy, label: Text("Privacy: ")) {
Text("Public ").tag("1")
Text("Private").tag("2")
}
.fixedSize()
.scaledToFit()
}
HStack{
Text("Attendance: ")
TextField("Max Attendents", text: $newEventMaxAttendents)
}
HStack{
DatePicker("Start Date ", selection: $newEventStartDate, displayedComponents: [.date])
}
.scaledToFit()
HStack{
DatePicker("Start Time ", selection: $newEventStartTime, displayedComponents: [.hourAndMinute])
}
.scaledToFit()
HStack{
DatePicker("End Date ", selection: $newEventEndDate, displayedComponents: [.date])
}
.scaledToFit()
HStack{
DatePicker("End Time ", selection: $newEventEndTime, displayedComponents: [.hourAndMinute])
}
.scaledToFit()
HStack{
Text("Price ")
TextField("Price", text: $newEventPrice)
}
HStack{
Picker(selection: $newEventType, label: Text("Type ")) {
Text("Private ").tag("1")
Text("Education ").tag("2")
Text("Concert ").tag("3")
Text("Festival ").tag("4")
Text("Food ").tag("5")
Text("Religious ").tag("6")
Text("Attraction").tag("7")
Text("Business ").tag("8")
}
.fixedSize()
}
}
// HStack for confirm and cancel buttons
HStack{
// BASH button
Button(action: {
print("Confirm")
}, label: {
Text("Confirm")
.font(.headline)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding()
.padding(.horizontal, 20)
.background{
Color.red
.cornerRadius(10)
.shadow(radius: 5)
}
}) // confirm button
// back button
Button(action: {
print("Back")
}, label: {
Text(" Back ")
.font(.headline)
.fontWeight(.semibold)
.foregroundColor(.white)
.padding()
.padding(.horizontal, 20)
.background{
Color.red
.cornerRadius(10)
.shadow(radius: 5)
}
}) // BASH button
} // HStack for confirm and back buttons
} // VStack
.ignoresSafeArea(.keyboard)
} // View
}

Centering DatePicker inside a section

Hello! I am trying to center the DatePicker inside the Section in SwiftUI. The screenshot shows the current display and desired display.
I've attempted the following and it doesn't seem to work:
putting DatePicker in VStack with .alignment as centered,
using .frame(alignment: .center) on the section,
and attempting to place center decorators to the DatePicker itself.
The first 2^ center the text within the section, but not the actual DatePicker object itself on the screen.
An explanation on how to do this, and what to know for future cases like these would be super helpful. Thank you!
NavigationView {
Form {
Section {
VStack(alignment: .center) {
DatePicker("Please enter a time", selection: $wakeUpTime, displayedComponents: .hourAndMinute)
.labelsHidden()
}
} header: {
Text("When do you want to wake up?")
.font(.headline)
}
.frame(alignment: .center)
.navigationTitle("BetterRest")
.toolbar {
Button("Calculate", action: calculateBedtime)
}
You can use a HStack with two Spacer to acomplish this output in SwiftUI.
NavigationView {
Form {
Section {
HStack{ //Convert to HStack
Spacer() //add this
DatePicker("Please enter a time", selection: $wakeUpTime, displayedComponents: .hourAndMinute)
.labelsHidden()
Spacer() // add this
}
} header: {
Text("When do you want to wake up?")
.font(.headline)
}
.frame(alignment: .center)
.navigationTitle("BetterRest")
.toolbar {
Button("Calculate", action: calculateBedtime)
}
}
}
Output:
Try following code:
var body: some View {
NavigationView {
Form {
Section {
DatePicker("Please enter a time",
selection: $wakeUpTime,
displayedComponents: .hourAndMinute)
} header: {
Text("When do you want to wake up?")
.font(.headline)
}
.frame(alignment: .center)
.navigationTitle("BetterRest")
.toolbar {
Button("Calculate") {
print("Calculate")
}
}
}
}
}

Picker support for iOS14 SwiftUI

I had my app working fine with SwiftUI and iOS13, and now I'm trying to add support to 14 and part of the app looks like this:
That gray are in the background shouldn't be there. I tried, setting the background to white inside the picker, removing some components, removing the frame and nothing works.
Here's the code:
ZStack {
if showingNewMealTime {
ZStack {
VStack(alignment: .center) {
ZStack{
Color.black.opacity(0.4)
.edgesIgnoringSafeArea(.vertical)
VStack(spacing: 20) {
Text("Change Time")
.bold().padding()
.frame(maxWidth: .infinity)
.background(Color.yellow)
.foregroundColor(Color.white)
HStack {
VStack {
Picker("", selection: $pickerHour){
ForEach(1..<12, id: \.self) { i in
Text("\(i)").tag(i)
}
}
.frame(width: 50, height: 120)
.clipped()
}
VStack {
Picker("", selection: $pickerMinutes){
ForEach(0..<60, id: \.self) { i in
Text("\(i)").tag(i)
}
}
.frame(width: 50, height: 120)
.clipped()
}
VStack {
Picker("", selection: $pickerAmOrPm[pickerAmOrPmSelection]){
ForEach(pickerAmOrPm, id: \.self) { i in
Text("\(i)").tag(i)
}
}
.frame(width: 50, height: 120)
.clipped()
}
}
Spacer()
Button(action: {
...
}){
Text("Save")
}
.padding(.horizontal)
.padding(.bottom, 30)
}
.frame(width:300, height: 300)
.background(Color.white)
.mask(RoundedRectangle(cornerRadius: 20))
.shadow(radius: 20)
}
}
}
}
}
What's changed and what do I have to fix to correct that gray area?
Thanks
Use the native DatePicker instead.
import SwiftUI
struct DatePickerView: View {
#State var date: Date = Date()
var body: some View {
VStack {
DatePicker("Date", selection: $date,
displayedComponents: .hourAndMinute)
.frame(height: 50)
Spacer()
}
.padding()
}
}
struct DatePickerView_Previews: PreviewProvider {
static var previews: some View {
DatePickerView()
}
}
Image showing the result of the above code
For more info:
SwiftUI DatePicker - swiftcompiled.com
Selecting dates and times with DatePicker - hackingwithswift.com
How to create a date picker and read values from it - hackingwithswift.com
DatePicker - Documentation
(Oct 11, 2020 Edit):
Edited adding links to more information.

SwiftUI passing a saved value to parent view

I am fairly new to SwiftUI I am trying to figure out the best way to pass data from a child view to parent?
Thanks for the help I come from a Javascript (React) background so this is a little different for me
The way my child view works is the user clicks on an image to select that image.
I have #State binding that saves the imgUrl which is a String referring to name in Assets.
I am just not sure about the best way to pass that value to the parent component.
Here is the child view (imageSelector)
struct ImageSelector: View {
#State private var windowImgs = ["1", "2", "3","4","5","6","7","8","9","10","11","12","13", "14","15","16","17","18"]
#State private var imgPicked = ""
var body: some View{
ScrollView(Axis.Set.horizontal, showsIndicators: true){
HStack{
ForEach(0..<18){num in
Button(action:{
self.imgPicked = self.windowImgs[num]
print(self.imgPicked)
}){
Image("\(self.windowImgs[num])")
.renderingMode(.original)
.resizable()
.cornerRadius(4)
.frame(width: 100, height: 100)
}
}
}
}
}
}
Here is the parent view (AddCounterForm)
struct AddCounterForm: View {
#Environment(\.presentationMode) var presentationMode
#State private var pickedImg: String = "defaultImg"
#State private var price: String = "0.0"
#State private var qty: String = "0"
var body: some View {
VStack (spacing: 40){
HStack {
Button("Cancel"){
self.presentationMode.wrappedValue.dismiss()
}
.foregroundColor(.red)
Spacer()
Button("Save"){
}
}
HStack {
VStack (spacing: 20){
TextField("Window type", text: /*#START_MENU_TOKEN#*//*#PLACEHOLDER=Value#*/.constant("")/*#END_MENU_TOKEN#*/)
TextField("Window location", text: /*#START_MENU_TOKEN#*//*#PLACEHOLDER=Value#*/.constant("")/*#END_MENU_TOKEN#*/)
}
.textFieldStyle(RoundedBorderTextFieldStyle())
Image(pickedImg)
.resizable()
.cornerRadius(4)
.frame(width: 90, height: 90)
.padding(.leading)
}
HStack {
Text("Price")
TextField("", text:$price)
.frame(width: 70)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numberPad)
Spacer()
Text("Qty")
TextField("", text:$qty)
.frame(width: 70)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numberPad)
}
VStack {
Text("Select an image")
.foregroundColor(.blue)
ImageSelector()
.padding(.bottom)
Button("Use your own image"){
//method
}
.frame(width: 180, height: 40)
.background(Color.blue)
.clipShape(Capsule())
.foregroundColor(.white)
.padding(.top)
}
}
.padding()
}
}
Solution for preview thanks for the help from #Asperi & #neverwinterMoon
struct ImageSelector_Previews: PreviewProvider {
static var previews: some View {
PreviewWrapper()
}
}
struct PreviewWrapper: View {
#State(initialValue: "") var imgPicked: String
var body: some View {
ImageSelector(imgPicked: $imgPicked)
}
}
In this case Binding is most appropriate
struct ImageSelector: View {
#Binding var imgPicked: String
and use
ImageSelector(imgPicked: $pickedImg)
.padding(.bottom)

How to change DatePicker's texts color in SwiftUI?

I saw this question but it doesn't work in SwiftUI.
Changing text color of datepicker
I tried .forgroundColor and .accentColor but they don't change the texts' color.
Using .colorInvert() and .colorMultiply(.white) will change the text color to white but won't work when the device is in Dark Mode. Instead, try this:
DatePicker("Date", selection: $selection)
.colorScheme(.dark) // or .light to get black text
I just simple set the accentColor and it works.
#State private var date = Date()
DatePicker("Select a date",
selection: $date, in: ...Date(),
displayedComponents: .date)
.labelsHidden()
.accentColor(.orange)
try this:
var body: some View {
Group {
DatePicker(selection: $selected) {
Text("Date")
}
.colorInvert()
.colorMultiply(Color.blue)
}
}
I use extension for customized text color for both of light mode and dark mode.
extension View {
#ViewBuilder func changeTextColor(_ color: Color) -> some View {
if UITraitCollection.current.userInterfaceStyle == .light {
self.colorInvert().colorMultiply(color)
} else {
self.colorMultiply(color)
}
}
}
and sample is as below.
DatePicker("Date", selection: $selection)
.labelsHidden()
.changeTextColor(.green)
you can do this to make the text appear white in light or dark mode if you use a background color
struct PickerDate: View {
#Environment(\.colorScheme) var colorScheme
#State var date: Date
var body: some View {
VStack {
DatePicker("Record Date", selection: $date, in: ...Date(), displayedComponents: .date)
.labelsHidden()
.colorMultiply(colorScheme == .dark ? .black : .white)
.colorInvert()
}
}
}
}
I found applying this modifier to the DatePicker to be cleaner:
Forces the color to white
.environment(\.colorScheme, .dark)
Forces the color to dark
.environment(\.colorScheme, .light)
DatePicker("DatePicker", selection: self.$date, displayedComponents: .hourAndMinute)
.labelsHidden()
.colorMultiply(Color.white)
.colorInvert()