Post

Replies

Boosts

Views

Activity

OS X + Swift + Xcode : Programmatically transition from one view controller to another
Hello, I have a swift program that allows me to transition from a primary view controller to a secondary view controller. To complete this task I create a segue between a button on the primary view controller and the secondary view controller by dragging from the button to the secondary view controller then assigning an identifier to this seque. The balance is handled programatically. What I would like to do is eliminate the creation of the segue via dragging and handle transitioning to the secondary view controller 100% in code. I have given the secondary view controller a storyboard id so it seems logical to me that I should be able to locate the secondary view controller via this identifier and use this to transition to it. Is there a way to do this? Regards, Chris
3
0
689
Aug ’21
SwiftUI + Xcode + OS X: Center container on screen
Hello, I have a Swift program. It utilizes the SwiftUI. I want to place my frame/container in the center of the computer screen. Any advise on how to do so would be appreciated. Below is what I have so far. Regards, Chris import SwiftUI @main struct Test1App: App {     var body: some Scene {         WindowGroup {             ContentView()         }     } } import SwiftUI struct ContentView: View {     var body: some View {         Text("Hello, world!")             .frame(width: 500, height: 350)             .background(Color .blue)             .padding()     } }
1
0
522
Aug ’21
Swift + OS X + Xcode : Change NavigationLink destination and text programtically
Hello, I am trying to learn Swift. I have the code below. With a button click I can move to a new view. What I would like to do is once the new view is displayed have the navigation link destination changed to "CurrentView" and the button text to "Previous View". Any insight on how to resolve this issue would be appreciated. Regards, Chris import SwiftUI struct ContentView: View {     var body: some View {         NavigationView {             NavigationLink(destination: NextContentView()){                 Text("Next View")             }         }     } }
6
0
1k
Aug ’21
Remove gap between lazyvgrids in vstack
Hello, I have the code below which creates a view. Unfortunately it puts a small gap between the two LazyVGrids that I would like to eliminate. Any suggestions would be appreciated. Below is my code. Chris import SwiftUI struct SecondView: View {          var columns = [         GridItem(.fixed(100), spacing: 0.1),         GridItem(.fixed(100), spacing: 0.1),         GridItem(.fixed(100), spacing: 0.1),         GridItem(.fixed(100), spacing: 0.1),         GridItem(.fixed(100), spacing: 0.1)     ]     let principalData: convertCSVtoArray          var body: some View {         let numArrays = principalData.cvsData.count         let numElementsPerArray = principalData.cvsData[0].count                      VStack{             Text("")             Text("Historical Data")                 .font(.title)                 .padding(5)             Divider()             LazyVGrid(                 columns: columns,                 alignment: .center,                 spacing: 0)             {                 ForEach(0..<1) {row in                     ForEach(0..<numElementsPerArray) {col in                         Rectangle()                             .foregroundColor(.white)                             .overlay (Text(principalData.cvsData[row][col]).bold())                             .frame(height: 30)                             .border(Color.gray, width: 2)                     }                 }             }             ScrollView{                 LazyVGrid(                     columns: columns,                     alignment: .center,                     spacing: 0)                     {                         ForEach(1..<numArrays) {row in                             ForEach(0..<numElementsPerArray) {col in                                 Rectangle()                                     .foregroundColor(.white)                                     .overlay (Text(principalData.cvsData[row][col]))                                     .frame(height: 30)                                     .border(Color.gray, width: 0.5)                             }                         }                     }                 ForEach(0..<30){index in                     Text("")                 }             }// end scrollview         }     } }
3
0
2.7k
Sep ’21
How can I set the position of an app window on the screen for macOS with Swiftui?
I am trying to determine how to set the initial position of an app window for macOS. I have tried using NSViewRepresentable and .setFrameTopLeftPoint with no success. Is my syntax incorrect to achieve the desired results or should I be looking at some other method? struct WindowAccessor: NSViewRepresentable { @Binding var window: NSWindow? func makeNSView(context: Context) -> NSView { let view = NSView() view.window?.setFrameTopLeftPoint(CGPoint(x: 600, y: 400)) DispatchQueue.main.async { self.window = view.window } return view } func updateNSView(_ nsView: NSView, context: Context) {} } and var body: some Scene { WindowGroup { ContentView() .background(WindowAccessor(window: $window)) }
0
0
664
Nov ’21
How do I configure the headings in a SwiftUI table.
Hello, The following code displays the correct data but I am unable to figure out how to format the tables headings , including font size and alignment. Any help in pointing me in the right direction will be appreciated. Chris struct SummaryTable: View { private var localArray: [TradingDayPrices] init(passedInArray: [TradingDayPrices]) { self.localArray = passedInArray } var body: some View { let funds: [Fund] = GetSummaryTable(localArray: localArray) Table(funds) { TableColumn("Index Fund") { value in Text(value.name) .padding(.vertical, 2) } .width(90) TableColumn("Shares") { value in HStack { Spacer() Text(value.shares) Spacer() } } .width(90) TableColumn("Share Price") { value in HStack { Spacer() Text(value.sharePrice) Spacer() } } .width(90) TableColumn("Total") { value in HStack { Spacer() Text(value.total) } } .width(110) TableColumn("One Year Gain") { value in HStack { Spacer() Text(value.percentChange) Spacer() } } .width(90) } // end table .tableStyle(.inset(alternatesRowBackgrounds: true)) .padding([.leading, .trailing], 185) .padding([.top], 30) .padding([.bottom], 700) } }
0
0
736
Jan ’23
Swift Core Data - Change Location of Persistent Store
I have a program that reads in CVS data and writes it to a core data persistent store. I would like to change the location of the persistent store. Per Apple docs it appears that I should be able to achieve this by overriding it in a sub class of NSPersistentContainer. Unfortunately I have been unable to figure how to do this. Below is my attempt. The Xcode error I get is "cannot call value of non-function type URL". final class CoreDataContainer: NSPersistentContainer { let storePathURL: URL = URL(string: "file:///Users/Chris/Developer/Persistent Store")! override class func defaultDirectoryURL() -> URL { return super.defaultDirectoryURL() .absoluteURL(storePathURL) } }
1
0
1.1k
Apr ’23
Swift - SQLite3 Wal Checkpoint -> Unsafe Pointer Parameter
I have a program that adds data from CSV files to core data. Once I have saved the managed object context to the persistent store I want to run a checkpoint to flush the contents of the WAL file into the SQLite file. I have added code to my class in an attempt to do so but am unable to determine on the line "sqlite3_wal_checkpoint( ...)" what to put in the unsafe pointer parameter (denoted with ??????? in the code). class UpdateCoreData: ObservableObject { @Published var isLoading: Bool = true var moc: NSManagedObjectContext init(moc: NSManagedObjectContext) { self.moc = moc Task { await IsDataStoreEmpty(moc: self.moc) let fund1 = CSVtoCoreData(fundName: "Fund1", fileName: "Fund1.csv") let fund2 = CSVtoCoreData(fundName: "Fund2", fileName: "Fund2.csv") let fund3 = CSVtoCoreData(fundName: "Fund3", fileName: "Fund3.csv") await fund1.CSVtoCoreDataG(moc: self.moc) await fund2.CSVtoCoreDataG(moc: self.moc) await fund3.CSVtoCoreDataG(moc: self.moc) do { try moc.save() } catch { print("Error saving. \(error)") } --- start of added code let fileURL = URL(fileURLWithPath: "/Users/Chris/Downloads/Persistent Store 2/Funds.sqlite") var dataBase: OpaquePointer? sqlite3_open(fileURL.path, &dataBase ) if sqlite3_open(fileURL.path, &dataBase) != SQLITE_OK { print("Unable to open sqlite file") } else { print("Succesfully opened sqlite file") } sqlite3_wal_checkpoint(dataBase, ??????? ) sqlite3_close(dataBase) --- end of added code DispatchQueue.main.async { self.isLoading = false } } } // end init }
0
0
577
May ’23
Create Spreadsheet Like Grid with SwiftUI
I have some test code in which I am attempting to create a spreadsheet style grid with data. The code creates a grid but I am unable to get the bottom border of one row to overlap the top border of the row below it but I can get it to work left to right with padding using a negative trailing border. Any assistance would be appreciated. Below is the code: import SwiftUI struct DateAndClose { let date: Date let close: Double } func BuildArray() -> [DateAndClose] { var dataArray: [DateAndClose] = [] dataArray.append(DateAndClose(date: Date(), close: 123.4)) dataArray.append(DateAndClose(date: Date() + 10, close: 245.8)) dataArray.append(DateAndClose(date: Date() + 30, close: 329.3)) dataArray.append(DateAndClose(date: Date() + 45, close: 438.9)) return dataArray } struct Test: View { let heading: String var body: some View { let moArray: [DateAndClose] = BuildArray() Text("") Text(heading) .font(.system(size: 18, weight: .bold, design: .default)) .foregroundColor(.blue) .padding(.trailing, 24) Text("") List(moArray, id: \.date) { element in ListRow1(element: element) } .frame(width: 250) .background(Color.gray) Spacer() } } struct ListRow1: View { let element: DateAndClose var body: some View { let theDate = dateToStringFormatter.string(from: element.date) let theClose = String(format: "$%.2f", element.close ) let frameWidth: CGFloat = 100 let frameHeight: CGFloat = 25 let trailingPadding: CGFloat = -8.55 let bottomPadding: CGFloat = -4.8 HStack(){ Spacer() Text(theDate) .font(.system(size: 14, weight: .regular, design: .default)) .background(.white) .frame(width: frameWidth, height: frameHeight, alignment: .center) .border(.black, width: 1) .padding(.trailing, trailingPadding) .padding(.bottom, bottomPadding) Text(theClose) .font(.system(size: 14, weight: .regular, design: .default)) .background(.white) .frame(width: frameWidth, height: frameHeight, alignment: .center) .border(.black, width: 1) .padding(.bottom, bottomPadding) Spacer() } } } let dateToStringFormatter: DateFormatter = { let result = DateFormatter() result.dateFormat = "MM/dd/yy" result.timeZone = TimeZone(secondsFromGMT: 0) return result }()
2
0
2.6k
Oct ’22
How do I pass an instance of a class between models in MVVM
I have a working program utilizing the MVVM architecture. There are 3 view models and 3 models. In the first model called I do some testing and would like to pass the result of that testing, a boolean, to the other two models. I have tried to create a class with a boolean, create an instance in the content view and pass it into one of the view models. I would then pass it into the corresponding model. Unfortunately I have been unable to get it to work i.e. pass an instance of the class into the view model. If you see a fix to this approach or have a better approach please let me know. The failure message I get is related to attempting to pass csvData to vooVM. The message is => Cannot use instance member 'csvData' within property initializer; property initializers run before 'self' is available. My Class that contains the boolean that would be set in the first model and passed to the two other models via their view models: class CSVData: ObservableObject {     var updated: Bool = false } My Struct Content View initial section: struct ContentView: View { var csvData: CSVData // The following line gives the above mentioned error message @StateObject private var vooVM = VOOVM(csvData: csvData) @StateObject private var vfiaxVM = VFIAXVM() @StateObject private var prinVM = PrincipalVM() @State private var selectedItemID: Int? let bottomPadding: CGFloat = 2 init() { self.csvData = CSVData() } var body: some View { My View Model initial section: class VOOVM: ObservableObject { var ContainerValues1: [CommonAttributes] = [] var ContainerValues5: [CommonAttributes] = [] var MinAndMaxClose1: [String:Double] = [:] var MinAndMaxClose5: [String:Double] = [:] private var vooModel: VOOModel = VOOModel() var symbol: String var shares: Double var csvData: CSVData init(csvData: CSVData) { self.csvData = csvData
1
0
522
Aug ’22
Creating Instance of Class of type NSWindowController
I have a program that allows me to programmatically bounce a ball around a window. Everything works as desired. What I would like to be able to do is work with the window itself to do such things as remove the title, change the background color and make it non resizable. I think I do this by creating a class of type NSWindosController which I have done. I create an instance of it in the ContentView but it does not work. Is my class wrong or am I not creating an instance in the right place or is there some other problem. Thank you. import Cocoa class WindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() window?.styleMask.remove(.titled) window?.styleMask.remove(.resizable) window?.backgroundColor = .red } } import SwiftUI struct ColorShading: Identifiable { let value: GraphicsContext.Shading let id = UUID() } struct ContentView: View { @State private var isPaused: Bool = true @State private var ballPosition = BallPosition() @State private var winController = WindowController() var body: some View { let ballColors = [ ColorShading(value: GraphicsContext.Shading.color(.orange)), ColorShading(value: GraphicsContext.Shading.color(.red)), ColorShading(value: GraphicsContext.Shading.color(.blue)), ColorShading(value: GraphicsContext.Shading.color(.green)), ColorShading(value: GraphicsContext.Shading.color(.gray)), ColorShading(value: GraphicsContext.Shading.color(.yellow)), ColorShading(value: GraphicsContext.Shading.color(.purple)) ] TimelineView(.animation(minimumInterval: 0.0001, paused: isPaused)) { timeline in Canvas { context, size in _ = timeline.date.timeIntervalSinceNow let circleDiameter: Double = (size.width * 0.2) let circleRadius: Double = circleDiameter / 2 if isPaused == true { ballPosition.updateBaseData(maxX: size.width, maxY: size.height, circleRadius: circleRadius) } let wheelOrigin = CGPoint(x: ballPosition.xPosition, y: ballPosition.yPostion) context.stroke( Path { path in path.addArc(center: wheelOrigin, radius: circleRadius, startAngle: .degrees(0), endAngle: .degrees(360), clockwise: false) }, with: ballColors[ballPosition.randomColor].value, lineWidth: 2 ) // end context stroke ballPosition.updatePosition() } // end canvas .frame(width: 800, height: 800) } // end time line view .onAppear() { Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in isPaused = false timer.invalidate() } // end timer } // end on appear } }
1
0
653
Mar ’23
SwiftUI - Accessing StateObject's Object Without Being Installed on a View
I have a core data program. I run my fetch request in a class i.e. a view model and assign it to a StateObject in the ContentView. When I attempt to use the fetch request results from the view model in a selected view, the DataTable, I get this message: Accessing StateObject's object without being installed on a View. This will create a new instance each time. Not sure what to do. Below is my code: struct ContentView: View { @Environment(\.managedObjectContext) var moc @State var selection: DataDisplayed? = nil @StateObject var dataViewModel: FetchCoreData = FetchCoreData() var body: some View { NavigationSplitView{ sidebarContent .navigationSplitViewColumnWidth(min: 200, ideal: 200, max: 200) } detail: { detailContent } .navigationSplitViewStyle(.balanced) .navigationTitle("Testing") .frame(width: 1000, height: 800) } } extension ContentView { @ViewBuilder var detailContent: some View { if let selection = selection { detailContent(for: selection) .buttonStyle(.bordered) } else { Text("Make A Selection") } } @ViewBuilder func detailContent(for screen: DataDisplayed) -> some View { switch screen { case .VOODT: DataTable(dataModel: dataViewModel.fetchRequest) case .NWDT: Text("Start") case .VOOG1: Text("VOO Graph 1 Year") default: Text("Not yet implemented") } } } class FetchCoreData: ObservableObject { @FetchRequest var fetchRequest: FetchedResults<TradingDayPrices> init() { _fetchRequest = FetchRequest<TradingDayPrices>(sortDescriptors: [NSSortDescriptor(key: "timeStamp", ascending: true)], predicate: NSPredicate(format: "net > %d", 0.0)) } } struct DataTable: View { var dataModel: FetchedResults<TradingDayPrices> init(dataModel: FetchedResults<TradingDayPrices>) { self.dataModel = dataModel } var body: some View {. // fails on this line ######################## List(dataModel.fetchRequest, id: \.self) { item in Text("\(dateToStringFormatter.string(from: item.timeStamp!)) - ") + Text("\(item.vooClose) ") } } }
2
0
2.0k
Apr ’23
Swift - Map two elements from an array to a new array
I have an array of core data entities, named TradingDayPrices, with 1 date and 4 double attributes. I would like to be able to copy the date value and 1 specific double into a new array. I have not been able to determine the correct syntax. With the code below I get the error "cannot assign value of type [[Any]] to type [Date:Double]" var allClosingValues: [TradingDayPrices] var closingValues: [Date:Double] var selection: DataDisplayed init(selection: DataDisplayed, allClosingValues: [TradingDayPrices]) { self.selection = selection self.allClosingValues = allClosingValues switch selection { case .VOODT: closingValues = allClosingValues.map { [$0.timeStamp! , $0.vooClose] } default: let _ = print("Error in Data Table Structure") } }
2
0
1.9k
Apr ’23
Swift - access attribute in array of core data entities in a table column via a variable
The below code works. I pass in an array of core data entities and display attributes in a table. In the second table column I use a switch case statement to handle the 3 possible attributes I want to display. I could eliminate the switch case if I could figure out how to access a given core data attribute via a variable that contains the specific attribute name but have been unable to determine how to do so. Two attempts are commented out in the code. struct DataTable: View { private var closingValues: Array<TradingDayPrices> var heading: String var attribute: String init(closingValues: [TradingDayPrices], heading: String, attribute: String) { self.closingValues = closingValues self.heading = heading self.attribute = attribute } var body: some View { Text(heading) .foregroundColor(.black) .font(Font.custom("Arial", size: 18)) .bold() .padding(.top, 10) Table(self.closingValues) { TableColumn("Date") { value in HStack { Spacer() Text(dateToStringFormatter.string(from: value.timeStamp!)) Spacer() } } .width(100) TableColumn("Closing Value") { value in HStack { Spacer() // Text(String(format: "$ %.2f", value(forKey: attribute))) // Text(String(format: "$ %.2f", value(attribute))) switch attribute { case "s1Close": Text(String(format: "$ %.2f", value.s1Close)) case "s2Close": Text(String(format: "$ %.2f", value.s2Close)) default: Text(String(format: "$ %.2f", value.s3Close)) } Spacer() } } .width(100) } .foregroundColor(.black) .font(Font.custom("Arial", size: 16)) .frame(width: 250) Spacer() .frame(height: 30) } }
1
0
883
Apr ’23