Post

Replies

Boosts

Views

Activity

Reply to Adding stacks to a stack view programmatically
it will add a horizontal stack view containing a label and a stepper Why don't you do it as you describe? 		func addButtons() { 				for (key,value) in feedInventory where value > 0 { 						let filteredProducts = feedProducts.filter { $0.code.contains(key)} 						for feedProduct in filteredProducts { 								let horizontalStack = UIStackView() 								horizontalStack.axis = .horizontal 								horizontalStack.alignment = .firstBaseline 								let label = UILabel(frame: .zero) 								label.text = " \(feedProduct.name) , amount: \(value)" 								//... 								label.widthAnchor.constraint(equalToConstant: 200).isActive = true 								horizontalStack.addArrangedSubview(label) 								let stepper = UIStepper(frame: .zero) 								//... 								stepper.accessibilityLabel = "\(feedProduct.code) up/down" 								horizontalStack.addArrangedSubview(stepper) 								feedStack.addArrangedSubview(horizontalStack) 						} 				} 		}
Topic: Programming Languages SubTopic: Swift Tags:
Feb ’21
Reply to Find which button is pressed in a Grid in SwiftUI
btw I changed the ObservableObjects to use generics. It doesn't seem to have an effect on functionality-wise.  When you make MenuViewObservable generic, better use the generic type as the argument type of the closure: class MenuViewObservableT: MenuItem: ObservableObject { var onButtonTap: ((T) - Void) = { _ in } //- Use `T`, not `MenuItem` } Shows the following error. I cannot reproduce the same error with your currently shown code. Something hidden in your project may be affecting. For example, don't you have another Menu type in you project, including imported modules?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to Find which button is pressed in a Grid in SwiftUI
Is there a way to actually get the type of the enum here? So I can do something like this. Unfortunately, with declaring var onButtonTap: ((MenuItem) - Void)!, you are disposing the type info to tell to Swift compiler. (By the way, you should not use implicitly unwrapped Optional here. Better use explicit Optional or non-Optional.) You can make MenuViewObservable generic: class MenuViewObservableItemType: MenuItem: ObservableObject { var onButtonTap: ((ItemType) - Void) = {_ in} } But this may or may not work depending on the actual usage of observable.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to Setting UILabels to Firestore data
”!=“ is not, right? Thats what I have learned.  Didn't you read my replies? Your code (updated one): 								if snapshot != nil { 										//Doing nothing when `snapshot` is *not nil* 								}else { 										//This code block is executed when `snapshot` *is nil* 										//... 								} is equivalent to: 								if snapshot == nil { 										//This code block is executed when `snapshot` *is nil* 										//... 								} You may need to learn how if-else works,
Topic: Programming Languages SubTopic: Swift Tags:
Feb ’21
Reply to Data.withUnsafeMutableBytes memory lifetime
Is it safe to assume that as long as my Swift object has a reference to the Data, the pointer will remain valid? Or, might Swift optimize it away? It is clearly documented such usage is unsafe: withUnsafeMutableBytes(_:) - https://developer.apple.com/documentation/foundation/data/1779823-withunsafemutablebytes Warning The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. f so, is there any way to insure the data remains available, other than making a copy within the C library?  You can make a copy within Swift: class EMsg { &#9;&#9;var em: UnsafeMutablePointer<T_EMsg>? &#9;&#9;var byteBuf: UnsafeMutableBufferPointer<UInt8> &#9;&#9; &#9;&#9;init?(_ data:Data) { &#9;&#9;&#9;&#9;self.byteBuf = .allocate(capacity: data.count) &#9;&#9;&#9;&#9;_ = self.byteBuf.initialize(from: data) &#9;&#9;&#9;&#9;self.em = emsg_read(byteBuf.baseAddress, byteBuf.count); &#9;&#9;} &#9;&#9; &#9;&#9;deinit { &#9;&#9;&#9;&#9;byteBuf.deallocate() &#9;&#9;&#9;&#9;//Some code to free em? &#9;&#9;&#9;&#9;//... &#9;&#9;} &#9;&#9; &#9;&#9;func process()&#9;{ &#9;&#9;&#9;&#9;guard let em = em else { return } &#9;&#9;&#9;&#9;emsg_process(em) &#9;&#9;} }
Topic: Programming Languages SubTopic: Swift Tags:
Feb ’21
Reply to Change VStack color with a button inside an HStack
Why don't you set the background color in the action of the button? struct ContentView: View { &#9;&#9; &#9;&#9;@State var index = 0 &#9;&#9;@State var vstackColor: Color? = .black &#9;&#9; &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;VStack{ &#9;&#9;&#9;&#9;&#9;&#9;Spacer() &#9;&#9;&#9;&#9;&#9;&#9;CustomTabs(index: $index, &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; color: $vstackColor) &#9;&#9;&#9;&#9;}.background(vstackColor ?? Color.black) &#9;&#9;} } struct CustomTabs : View { &#9;&#9; &#9;&#9;@Binding var index : Int &#9;&#9;@Binding var color: Color? &#9;&#9; &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;HStack{ &#9;&#9;&#9;&#9;&#9;&#9;Button(action: { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.index = 0 &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.color = .red //Other color &#9;&#9;&#9;&#9;&#9;&#9;}) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Spacer() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Image("fdt") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Spacer() &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9;&#9;} }
Feb ’21
Reply to Any examples of IKSaveOptions() / NSSavePanel() filetype selectors out there?
let me know if something rings a bell? You are not using the documented initializer of IKSaveOptions. init(imageProperties:imageUTType:) - https://developer.apple.com/documentation/quartz/iksaveoptions/1503412-init let panel = NSSavePanel() let options = IKSaveOptions(imageProperties: [:], imageUTType: kUTTypeImage as String)! options.addAccessoryView(to: panel) panel.begin { response in if response == .OK, let savePath = panel.url { //... } }
Topic: UI Frameworks SubTopic: AppKit Tags:
Feb ’21
Reply to Error when taking out unused variable
In the latest code for AddView , colorScheme is used. As far as I tried (keep using colorScheme and removing the line @Environment(\.colorScheme) var colorScheme), I can reproduce the same error. Check if the variable is really unused, before removing the declaration.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to variable in func not working
a error that says Cannot find 'textfield' in scope here is the is the code. Isn't it Cannot find 'test' in scope? In your current code (please use Code block), testfunc() is places outside of ContentView, so its property test is not visible there: struct ContentView: View { @State var test = "this is a test" var body: some View { Text("Hello") } //- End of `body` } //- End of `ContentView` func testfunc() { test = "test" } If you want to write a function which modifies some instance property, it needs to be placed inside the same type: struct ContentView: View { @State var test = "this is a test" var body: some View { Text("Hello") } //- End of `body` func testfunc() { test = "test" } //- End of `testfunc()` } //- End of `ContentView`
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to Changing a value with the stepper
struct FeedProduct { Thanks. If you created a new project and copied the code in your opening post, you would have found what were missing more easily. I can't use = Int(sender.value) because this resets to 0 each time I press the button, I guess you cannot use = Int(sender.value) because you are not setting the value property of the stepper. how can I update the values without using removeButtons() and addButtons()? You just need to update the text property of the corresponding UILabel in the action method stepperValueChanged. To achieve this, you need to access the right UILabel in that method. To make things easier, you can encapsulate each row into a class: LabelStepper.swift import UIKit class LabelStepper: UIStackView { typealias ActionHandler = (LabelStepper)-Void /// A handler called on `.valueChanged` of `stepper` var onValueChanged: ActionHandler? let label: UILabel let rationAmount: UILabel //- The right UILabel let stepper: UIStepper init(text: String, value: Int, onValueChanged: ActionHandler?) { let label = UILabel(frame: .zero) let rationAmount = UILabel(frame: .zero) let stepper = UIStepper(frame: .zero) self.label = label self.rationAmount = rationAmount self.stepper = stepper self.onValueChanged = onValueChanged super.init(frame: .zero) let horizontalStack = self horizontalStack.axis = .horizontal horizontalStack.alignment = .firstBaseline //- You can try other values... //horizontalStack.distribution = .fillEqually label.text = text horizontalStack.addArrangedSubview(label) rationAmount.text = "\(value)" horizontalStack.addArrangedSubview(rationAmount) stepper.value = Double(value) //- Please do not forget to set `value` stepper.minimumValue = 0 stepper.maximumValue = 900 stepper.wraps = false stepper.autorepeat = false stepper.addTarget(self, action: #selector(stepperValueChanged(_:)), for: .valueChanged) horizontalStack.addArrangedSubview(stepper) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func stepperValueChanged(_ sender: UIStepper) { rationAmount.text = "\(Int(sender.value))" //- Update the `text` property of the right UILabel onValueChanged?(self) } } And use it in the VC: func addButtons() { for (feed,amount) in feedInventory where amount 0 { let filteredProducts = feedProducts.filter { $0.code.contains(feed)} for feedProduct in filteredProducts { let rationIndex = rationArrayPosition[feedProduct.code]! let value = myHorses[horseIndex].ration[rationIndex] let horizontalStack = LabelStepper( text: "\(feedProduct.name)", value: value ) {labelStepper in myHorses[horseIndex].ration[rationIndex] = Int(labelStepper.stepper.value) } horizontalStack.stepper.accessibilityLabel = "\(feedProduct.code)" feedStack.addArrangedSubview(horizontalStack) } } }
Topic: Programming Languages SubTopic: Swift Tags:
Feb ’21
Reply to Updating item in nested observed array with swiftUI
Is there a simpler way to eliminate the keeping track of all the indices. As far as I know, there are no ways provided in the current SwiftUI framework. You would be able to create some wrapper to make things look simpler, for example: struct ForEachMutableData, Content: View: DynamicViewContent where Data : RandomAccessCollection &amp; MutableCollection, Data.Index: Hashable { var data: Data { dataBinding.wrappedValue } var dataBinding: BindingData var content: (BindingData.Element)-Content init(_ dataBinding: BindingData, content: @escaping (BindingData.Element)-Content) { self.dataBinding = dataBinding self.content = content } var body: some View { ForEach(data.indices, id: \.self) {index in content(dataBinding[index]) } } } And use it as: var body: some View { VStack (alignment: .leading) { List { ForEachMutable($eventsVM.events) { eventBinding in VStack { Text(eventBinding.wrappedValue.title) .font(.title) Text("items todo: \(eventBinding.wrappedValue.totalTodos)") .font(.title3) ForEachMutable(eventBinding.todos) { todoBinding in HStack { Image(systemName: todoBinding.wrappedValue.done ? "checkmark.square" : "square") .resizable() .frame(width: 24, height: 24) .foregroundColor(todoBinding.wrappedValue.done ? .blue : .gray) .font(.system(size: 20, weight: .regular, design: .default)) Text(todoBinding.wrappedValue.title) Spacer() }.padding(5.0) .onTapGesture(perform: { todoBinding.wrappedValue.done.toggle() }) } } } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to Find which button is pressed in a Grid in SwiftUI
But it's giving me the following error. In Swift, nested type does not work as a constraining something, but is just a namespace. If you want to put some constraint for the generic argument, you may need to introduce another protocol: protocol MenuItem {} extension Menu.UserType: MenuItem {} extension Menu.Main: MenuItem {} struct MenuButtonItemType: MenuItem: View { //... }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21
Reply to .debounce() not working as expected
I am trying to debounce the API call when a user enters something in TextField. Not clear enough, but I guess you should better make the TextField change as a publisher and apply debounce on it. As described in the documentation - https://developer.apple.com/documentation/combine/fail/debounce(for:scheduler:options:%29 This operator is useful to process bursty or high-volume event streams where you need to reduce the number of values delivered to the downstream to a rate you specify. dataTaskPublisher emits only one event, not bursty nor high-volume event streams.
Topic: Programming Languages SubTopic: Swift Tags:
Feb ’21
Reply to Broken NavigationLink behavior when using @StateObject and a ForEach inside a Form
Can anything advise if there is a logical issue with the code or is it a SwiftUI bug? Very likely a big flaw in the current implementation of SwiftUI. Better send a feedback to Apple. Any suggestions for a workaround? Moving the NavigationLink out of Form looks like working in a simple case. struct MainView: View { @StateObject var viewModel = ViewModel() var body: some View { NavigationView { ZStack { NavigationLink ( destination: ChildView(isActive: $viewModel.isActive), isActive: $viewModel.isActive, label: { EmptyView() } ) Form { HStack { Text("Go to child view") Spacer() Image(systemName: "chevron.forward") } .contentShape(Rectangle()) .onTapGesture { print(viewModel.isActive) viewModel.isActive = true } ForEach(1..4) { Text("\($0)") } } } .navigationBarTitle("Test") } } } There may be other better workarounds, but I could not find any till now.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Feb ’21