Hello
How can I remove the Collapse button that is on the navigationBar in iPadOS?
Thank You!
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
I am using a SwiftUI @FetchRequest to displays Core Data items, one of the properties of the entity is date, and I want to filter items by today's Date, this is the @FetchRequest:
@FetchRequest(
entity: Book.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Book.date, ascending: true)],
predicate: NSPredicate(format: "date == %@"),
animation: .default)
var books: FetchedResults<Book>
How do I complete the NSPredicate to make it work? (I know that there are no arguments in the predicate yet)
Thank You!
Hello
If I have this array:
var objects = [
Object(value: 100, date: Date(), imageTemplate: "30"),
Object(value: 200, date: Date(), imageTemplate: "20"),
Object(value: 400, date: Date() + 84000, imageTemplate: "10")
]
How can I count how many different dates are in the array using NSPredicate?
In this case it should return 2.
Thank You!
Hello
I am using CoreData in my App and want to save a single Picker value. I could create an entity with an Integer attribute and always edit the first object in the EntityList. But that doesn't sound like a clean solution.
The Picker is placed inside a settings view and has to be synced with iCloud.
Is there a simple way to do this?
Thank You
Hello
I created a simple SwiftUI app with Core Data and I want to be able to add data via the shortcuts app, I created a shortcut that takes some text as input and returns it in uppercase and when I run the shortcut in the shortcuts app, it works, however when I added an "add" function (to save data in the Core Data database) to the intent handle function, and I run it again nothing is saved in the app, here is the code:
class MakeUppercaseIntentHandler: NSObject, MakeUppercaseIntentHandling {
let persistenceController = PersistenceController()
func handle(intent: MakeUppercaseIntent, completion: @escaping (MakeUppercaseIntentResponse) -> Void) {
if let inputText = intent.text {
let uppercaseText = inputText.uppercased()
completion(MakeUppercaseIntentResponse.success(result: add(text: uppercaseText)))
} else {
completion(MakeUppercaseIntentResponse.failure(error: "The text entred is invalid"))
}
}
func resolveText(for intent: MakeUppercaseIntent, with completion: @escaping (MakeUppercaseTextResolutionResult) -> Void) {
if let text = intent.text, !text.isEmpty {
completion(MakeUppercaseTextResolutionResult.success(with: text))
} else {
completion(MakeUppercaseTextResolutionResult.unsupported(forReason: .noText))
}
}
func add(text: String) -> String{
let newItem = Item(context: persistenceController.container.viewContext)
newItem.text = text
do {
try persistenceController.container.viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return text
}
}
Thank You
Hello
I'm trying to compose a layout using the Layout API.
I have already written the code for both the Layout Stack I want to use and the view I am using it in, however I am getting an "Extra trailing closure passed in call" error in the view I am using the Stack in.
Here is the code:
import SwiftUI
struct StairsView: View {
var body: some View {
Group{
MyStairsStack{
Text("Hello, World!")
Text("Hello, World!")
Text("Hello, World!")
}
}
}
}
struct MyStairsStack: Layout{
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) -> CGSize {
return .init(width: proposal.width ?? 0, height: proposal.height ?? 0)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Void) {
guard !subviews.isEmpty else { return }
let viewSize = maxSize(subViews: subviews)
var origin = bounds.origin
let maxWidth = bounds.width
subviews.forEach { view in
if (origin.x + (viewSize.width + 10) >= maxWidth){
origin.x = bounds.origin.x
}
view.place(at: origin, proposal: proposal)
origin.x += (viewSize.width + 10)
origin.y += (viewSize.height + 10)
}
}
private func maxSize(subViews: Subviews) -> CGSize{
subViews.map { $0.sizeThatFits(.unspecified) }.reduce(.zero) { currentMax, subviewSize in
CGSize(
width: max(currentMax.width, subviewSize.width),
height: max(currentMax.height, subviewSize.height))
}
}
}
The error is at line 5
Thank You for your time
Hello
When I write decimal numbers in my SwiftUI app, the app doesn't detect the comma ( , )
How do I solve it? (I'm using a DecimalPad)
Thank you
Hello
When I dismiss my .sheet it is very slow and sometimes it doesn't work
.sheet(isPresented: $myViewi) {
MyView()
}
@Environment(\.presentationMode) var presentationMode
.navigationBarItems(trailing:
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "xmark").font(.title).foregroundColor(.blue)
}
)
How do I fix it?
Thank You
Hello
How do I make the default placeholder of a CustomTextField (that has a double binding) a string (onAppear)
When I run the app on the TextField I see 0 instead of "Input"
Code:
import SwiftUI
struct BMIView: View {
var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = .current
formatter.numberStyle = .decimal
return formatter
}
@State private var height: Double?
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your height in cm")){
DecimalTextField("Input", value: $height.bound, formatter: currencyFormatter)
}
}
.navigationBarTitle("BMI")
}
}
}
struct DecimalTextField: UIViewRepresentable {
private var placeholder: String
@Binding var value: Double
private var formatter: NumberFormatter
init(_ placeholder: String,
value: Binding<Double>,
formatter: NumberFormatter ) {
self.placeholder = placeholder
self._value = value
self.formatter = formatter
}
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = .decimalPad
textfield.delegate = context.coordinator
textfield.placeholder = placeholder
textfield.text = formatter.string(for: value) ?? placeholder
textfield.textAlignment = .left
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done,
target: self, action: #selector(textfield.doneButtonTapped(button:)))
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,
target: nil,action: nil)
toolBar.setItems([space, doneButton], animated: true)
textfield.inputAccessoryView = toolBar
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
// Do nothing, needed for protocol
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: DecimalTextField
init(_ textField: DecimalTextField) {
self.parent = textField
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// Allow only numbers and decimal characters
let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
let withDecimal = (
string == NumberFormatter().decimalSeparator &&
textField.text?.contains(string) == false
)
if isNumber || withDecimal,
let currentValue = textField.text as NSString?
{
// Update Value
let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
let decimalFormatter = NumberFormatter()
decimalFormatter.locale = Locale.current
decimalFormatter.numberStyle = .decimal
// Try currency formatter then Decimal formatrer
let number = self.parent.formatter.number(from: proposedValue) ?? decimalFormatter.number(from: proposedValue) ?? 0.0
// Set Value
let double = number.doubleValue
self.parent.value = double
}
return isNumber || withDecimal
}
func textFieldDidEndEditing(_ textField: UITextField,
reason: UITextField.DidEndEditingReason) {
// Format value with formatter at End Editing
textField.text = self.parent.formatter.string(for: self.parent.value)
}
}
}
// MARK: extension for done button
extension UITextField{
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}
extension Optional where Wrapped == Double {
var _bound: Double? {
get{
return self
}
set{
self = newValue
}
}
var bound: Double {
get{
return _bound ?? 0
}
set {
_bound = newValue
}
}
}
The problem might be at line 243
(I found the struct DecimalTextField on the internet)
Thank you for your time
Hello
Everytime I run a project I get this popup: The document “iosfwd” could not be saved. You don’t have permission.
How do I fix it?
Thank you
Hello
I'm trying to use a formatter on a String but it is giving me this error
Cannot convert value of type 'String' to type 'NSNumber' in coercion, is there a simple and short way to fix it?
Here is the code
import SwiftUI
struct TemperatureView: View {
		
		@State private var inputValue = ""
		
		 let inputUnits = [
				"celsius [°C]",
				"kelvin [K]",
				"fahrenheit [°F]"
		]
		let outputUnits = [
				"celsius [°C]",
				"kelvin [K]",
				"fahrenheit [°F]"
	 ]
		@State private var inputUnitValue = 0
		
		@State private var outputUnitValue = 1
		
		
		var after: String{
				var input: Measurement<UnitTemperature>
				var output: String = ""
				
				switch inputUnits[inputUnitValue] {
				case "celsius [°C]": input = Measurement(value: Double(inputValue) ?? 0, unit: .celsius)
				case "kelvin [K]": input = Measurement(value: Double(inputValue) ?? 0, unit: .kelvin)
				case "fahrenheit [°F]": input = Measurement(value: Double(inputValue) ?? 0, unit: .fahrenheit)
				default: input = Measurement(value: Double(inputValue) ?? 0, unit: UnitTemperature.celsius)
				}
				switch outputUnits[outputUnitValue] {
				case "celsius [°C]": output = outputFormatter.string(from: input.converted(to: .celsius))
				case "kelvin [K]": output = outputFormatter.string(from: input.converted(to: .kelvin))
				case "fahrenheit [°F]": output = outputFormatter.string(from: input.converted(to: .fahrenheit))
				default: output = String(describing: input.converted(to: UnitTemperature.celsius))
						
				}
						
				return output
		}
		
		@Environment(\.presentationMode) var presentationMode
		let outputFormatter: MeasurementFormatter = {
						let nf = NumberFormatter()
						nf.locale = Locale.current
						nf.usesSignificantDigits = true
						let mf = MeasurementFormatter()
						mf.numberFormatter = nf
						mf.unitOptions = .providedUnit
						return mf
				}()
				
		var body: some View {
				NavigationView{
						Form{
								Section(header: Text("Enter your Input value")){
												TextField("Have a goal?", text: $inputValue)
														.keyboardType(.decimalPad)
								}
								
								Section(header: Text("Input")){
										Picker("Input values", selection: $inputUnitValue){
												ForEach(0..<inputUnits.count){ item in
														Text(inputUnits[item])
												}
										}
								}
								
								Section(header: Text("Output")){
										Picker("Output values", selection: $outputUnitValue){
												ForEach(0..<outputUnits.count){ item in
														Text(outputUnits[item])
												}
										}
								}
								
								Section(header: Text("Check your Output value")){
										Text("\(after as NSNumber, formatter: outputFormatter)")
								}
								
						}
						.navigationBarTitle("Temperature")
						.navigationBarItems(trailing:
																		Button(action: {
																				presentationMode.wrappedValue.dismiss()
																		}) {
																				Image(systemName: "xmark").font(.title).foregroundColor(.blue)
																		}
						)
				}
		}
		
}
The error is at line 80/81
Thank you for your time
Hello
I made a custom Picker View but I don't have any idea on how to change the background color to grey when I press on one of the options
Here is the code:
struct PickerView: View {
		
		var arr: [String] = ["Easy", "Medium", "Hard"]
		var h: CGFloat = 50
		var w: CGFloat = 320
		
		@ObservedObject var input: UserInput
		var body: some View{
				HStack(spacing: 40){
						ForEach(0..<arr.count){ i in
								HStack(spacing: 25){
										Text(arr[i])
												.bold()
												.onTapGesture {
														switch i{
														case i: input.indi = i
														default: return
														}
														print(i)
												}
										if(i < arr.count - 1){
										Divider()
												.frame(height: 25)
										}
								}
						}
				}.padding()
				.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
				.overlay(
						RoundedRectangle(cornerRadius: 16)
								.stroke(Color.gray, lineWidth: 3)
				)
		}
}
class UserInput: ObservableObject {
		@Published var indi: Int = 0
}
Thank you for your time
Hello
Is there a way to know if the detected finger or face are wrong?
I am using this function:
func authenticate() {
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "We need to unlock your data."
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
DispatchQueue.main.async {
if success {
self.isUnlocked = true
} else {
userPressedCancel = false
}
}
}
} else {
}
}
Hello
Is there a way to execute a function (even if the app is closed) at a certain time, for example 12:30 AM?
Hello
I am trying to save some data in the Health App from my app, and it is working, the problem is that when I delete that data (already saved) from my app (using the deleteFromHealthKit function) the data is not deleted from the health app. How can I fix this?
Here is the code:
import SwiftUI
import HealthKit
struct ContentView: View {
init() {
//--------
let healthStore = HKHealthStore()
let allTypes = Set([HKObjectType.quantityType(forIdentifier: .dietaryWater)!])
healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
if !success {
print("success")
}
}
}
func fetchHealthData(date: Date, ml: Double) -> Void {
let healthStore = HKHealthStore()
let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)
let waterConsumed = HKQuantitySample.init(type: quantityType!, quantity: .init(unit: HKUnit.literUnit(with: .milli), doubleValue: ml), start: date, end: date)
healthStore.save(waterConsumed) { success, error in
if (error != nil) {
print("Error: \(String(describing: error))")
}
if success {
print("Saved: \(success)")
}
}
}
@State var water: [Water] = []
@State private var value: Double = 0
func deleteFromHealthKit(date: Date, ml: Double) {
let healthStore = HKHealthStore()
let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)
let waterConsumed = HKQuantitySample.init(type: quantityType!, quantity: .init(unit: HKUnit.literUnit(with: .milli), doubleValue: ml), start: date, end: date)
healthStore.delete(waterConsumed) { success, error in
if (error != nil) {
print("Error: \(String(describing: error))")
}
if success {
print("Saved: \(success)")
}
}
}
var body: some View {
NavigationView{
VStack{
Text("Value: \(value)")
.padding()
HStack{
Text("100 ml")
.onTapGesture {
value = 100
}
Text("200 ml")
.onTapGesture {
value = 200
}
}
Button("Add"){
water.append(Water(value: value, date: Date()))
fetchHealthData(date: Date(), ml: value)
}.disabled(value == 0 ? true : false)
.padding()
List{
ForEach(0..<water.count, id: \.self){ i in
HStack{
Text("\(water[i].value)")
Text("\(water[i].date)")
}
.onTapGesture {
deleteFromHealthKit(date: water[i].date, ml: water[i].value)
water.remove(at: i)
}
}
}
}
}
}
}
struct Water: Identifiable {
var id = UUID()
var value: Double
var date: Date
}
Thank you