Post

Replies

Boosts

Views

Activity

How can I access an array in one of my classes?
myGV is a structure where I store a handful of global variables. The following are all sub-classes of SKSpriteNode: I have a class called guessingBar which holds 6 guessSlots. The former class has an array of the guessSlots for me to loop through. I just don't know the syntax of how to access the array. myGV holds multiple variables, so the SKSpriteNode guessBar can be found at: myGV.guessBar I expected to be able to read the array with: myGV.guessBar.guessSlots[x] but as you can see from the debugger screenshot, I cannot. In the screenshot you can see that everything is initialized. Am I missing some silly typo, or is the syntax escaping me? http: //98.7.37.117/s.png
3
0
618
Jun ’21
How can I pass a function pointer in Swift?
I would like to take this sample code override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .greenColor() button.setTitle("Test Button", forState: .Normal) button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside) self.view.addSubview(button) } func buttonAction(sender: UIButton!) { print("Button tapped") } ...and place the code to create the button in another file. So it would look more like this: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() makeButton(vControl: self) } @objc func buttonAction(sender: UIButton!) { print("Button tapped") } } Of course the main flaw is that I would have to pass a pointer to the function buttonAction. Something like we do in C makeButton(vControl: self, bFunc: &buttonAction) Have Googled a lot but can't seem to find the way to do this. How do I set up the makeButton page to recieve this? func makeButton (vControl: ViewController, bFunc: ???) What would the ??? be in reality? thanks
3
0
1k
Oct ’21
How can I use a custom image for a Swift button but still control the text separately?
Below is a simple code patch I use to create a custom button, am new at this. I noticed the text does not appear and am wondering what the proper method is for making the text appear? func makeButton (vControl: ViewController, action: Selector) { let myButtonImage = UIImage(named: "Picture1.png") let imageScale = myButtonImage!.size.width / myButtonImage!.size.height let wwidth = vControl.self.view.bounds.width let button = CreateButton(frame: CGRect(x: 100, y: 100, width: (myButtonImage?.size.width)!/3, height: (myButtonImage?.size.height)!/3)) button.setImage(myButtonImage, for: .normal) button.backgroundColor = .clear button.setTitleColor(.black, for: .normal) button.setTitle("Test Button", for: .normal) button.addTarget(vControl, action: action, for: .touchUpInside) vControl.view.addSubview(button) button.center = vControl.view.center }
3
0
2.0k
Oct ’21
Why does a dismissed child UIView doesn't reappear properly after its first appearance?
Thanks to people on this board I am able to successfully calla up a child UIViewConroller via animation with: This is the buttonAction from the Main UIViewController, which calls up setController @objc func buttonAction(sender: UIButton!) { guard let theButton = sender as? MyButton else { return} UIView.transition(with: self.view, duration: 0.5, options: .transitionCurlDown, animations: { [self] in self.addChild(setController); self.view.addSubview(setController.view); }, completion: { [self]_ in setController.didMove(toParent: self); setController.doLayout();}) } the doLayout method lies within the child: func doLayout (){ guard let parent = cView!.view.superview else {return} //make sure UIV honors safeAreaLayouts setConstraints(vc: self, pc: parent) } A button within the child, setController, dismisses itself: @objc func buttonAction(sender: UIButton!) { self.willMove(toParent: nil) self.removeFromParent() self.view.removeFromSuperview() self.dismiss(animated: false, completion: nil) } Everything works great the first time I call up the child UIView. It curls down while covering the first/parent UIVIEW, etc. etc. Figure 1 But after I dismiss the child view and call it again, the child view scrolls down without really covering the main view, it's like a mishmash. Figure 2 Only after all is said and done, then the child view covers everything. So am curious if I am dismissing something incorrectly.
3
0
775
Dec ’21
Can I create a class instance using DispatchQueue.global().async and have its methods run asynchronously?
I created the playground below to answer my question "If I created a class instance using DispatchQueue.global().async would that class remain in its own asynchronous queue? Even if the main app called one of that classes methods, would that method run asynchronously compared to the main app? With the sleep line I discovered that the answer is "no." But I am curious if there is a legit way to do this? Or even if there is, it is considered bad programming? import UIKit class MyFunx : NSObject { var opsCount = 0 override init() { super.init() } func addValues (a: Int, b: Int) { let c = a + b opsCount += 1 sleep(1) } } var firstVar = 0 var secondVar = 0 var myFunx : MyFunx? while secondVar < 100 { print ("starting") if myFunx == nil { print ("making myFunx") DispatchQueue.global().async { myFunx = MyFunx() } } else { myFunx!.addValues(a: firstVar, b: secondVar) } firstVar += 1 secondVar += 1 } print ("myFunx = \(myFunx)") print ("\(myFunx?.opsCount)") print ("exiting")
3
0
774
Jan ’22
How can I get my app to wait for a permission request to complete?
Am working on a recording app from scratch and it just has the basics. Within my info.plist I do set Privacy - Microphone Usage Description Still, I always want to check the "privacy permission" on the microphone because I know people can hit "No" by accident. However, whatever I try, the app keeps running without waiting for the iOs permission alert to pop up and complete. let mediaType = AVMediaType.audio let mediaAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: mediaType) switch mediaAuthorizationStatus { case .denied: print (".denied") case .authorized: print ("authorized") case .restricted: print ("restricted") case .notDetermined: print("huh?") let myQue = DispatchQueue(label: "get perm") myQue.sync { AVCaptureDevice.requestAccess(for: .audio, completionHandler: { (granted: Bool) in if granted { } else { } }) } default: print ("not a clue") }
3
0
1.6k
Feb ’22
Getting strange message in debugger since Xcode last updated
Xcode updated yesterday, and am now at Xcode Version 13.3 (13E113) Since then, whenever I debug my app the the simulator, I get the message below. Am curious if I should be concerned. If it makes a difference: Yes, I have an IBM keyboard attached via USB. Also this does not happen when I debug the app on the iPhone itself. 2022-03-15 14:50:45.745237-0400 Hello World[48883:648134] [HardwareKeyboard] -[UIApplication getKeyboardDevicePropertiesForSenderID:shouldUpdate:usingSyntheticEvent:], failed to fetch device property for senderID (778835616971358211) use primary keyboard info instead.
3
1
7.1k
May ’22
What is the difference between func (to view: UIView) and not using the 'to'?
I have a function in my UIView extension and I can call it both ways This way: func anchorSizePercent(to view: UIView, sFactor: CGSize) { ... } myHeader.anchorSizePercent(to: myView, sFactor: CGSize(width: 0.8, height: 0.2)) As well, I can call it without the to, such as: func anchorSizePercent(view: UIView, sFactor: CGSize) { ... } myHeader.anchorSizePercent(view: myView, sFactor: CGSize(width: 0.8, height: 0.2)) May I ask what the difference is?
3
0
496
Mar ’22
Am unable to receive HTTP responses with UIViewController set as URLSessionDelegate
This question is also, here, one StackOverflow. But it's only gotten 8 views, and I am stuck till I find out what am I doing wrong. I am able to create a URLSesion, build a request with a file to upload and successfully call it from my app. On my server side, the proper script is called, uploaded file is saved, etc,. However, I am not receiving the HTTP responses, data, etc. Actually had this working without the delegate, when the HTTP response functions were within the task itself. But am now trying to expand functionality and am missing something while trying implement the delegate. The trimmed code is below, and it all works, with the exception of setting up UIViewController as the URLSession delegate. Just trying to figure out why my UIViewController is not receiving the HTTP responses. Below is the code for: UIViewController Class which creates the upload session (UploadService) Extension for UIViewController which I want to use to process the responses How the previous task looked, when it worked. Before I tried to implement the delegate. UIViewController class UploadInv : UIViewController { var xFile : XFile? ...create UI.... let uploadService = UploadService() lazy var uploadSession: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: self, delegateQueue: .main) }() override func viewWillAppear(_ animated: Bool) { ... } override func viewDidLoad() { super.viewDidLoad() uploadService.uploadSession = uploadSession ... code the lays out all buttons, labels, etc... } @objc func buttonAction(sender: UIButton!) { guard let theButton = sender else { return} let myTag = theButton.tag switch myTag { //button to start upload case ButtType.up.rawValue: uploadService.start(upFile: xFile!, script: "uploadOrig.pl", upLoadInvClass: self) uploadService.task?.resume() //button to select file to upload case ButtType.file.rawValue: ... file xFile with file info } } UploadService class UploadService { var task: URLSessionUploadTask? var uploadSession = URLSession.shared func start(upFile: XFile, script: String, upLoadInvClass: UploadInv) { var request = upFile.makeUrlReq(upFile: upFile, script: script) self.task = uploadSession.uploadTask(with: request, from: request.httpBody! ) } } extension extension UploadInv: UIDocumentPickerDelegate, URLSessionDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { ... file xFile info for upload .... ... http request created .... } // Below are the three simple functions which I would handle // responses the server, but these never seem to get called. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { print("Error: \(err.localizedDescription)") } } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { print("didReceive response") completionHandler(URLSession.ResponseDisposition.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print("didReceive data") if let responseText = String(data: data, encoding: .utf8) { print(responseText) } } } Pre-Delegate model which worked class UploadService { var uploadSession = URLSession.shared func start(upFile: XFile, script: String, upLoadInvClass: UploadInv) { var request = upFile.makeUrlReq(upFile: upFile, script: script) uploadSession.uploadTask(with: request, from: request.httpBody ) { (data, response, error) in if let response = response { upLoadInvClass.upResp(resp: response) } if let error = error { upLoadInvClass.upErr(error: error) } if let data = data { upLoadInvClass.upData(data: data) } }.resume() } }
3
0
1.1k
May ’22
Is there an order for response, data, and error in URLSession delegates?
_Posted this here, on Stackoverflow. But after 2+ weeks got only 10 views and no responses. _ I have my URLSession delegates working, but am curious about the order I get back response, data, and error. Right now am testing purposeful errors on my server side, so I can check the response if it's not 200. If it's not, I do not need to process the data, etc. So I could use a flag, but have to make sure that I'l always get response, data, and error in a specific order? Does such an order exist? extension UploadInv: UIDocumentPickerDelegate, URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate { // Error received func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { print("Error: \(err.localizedDescription)") } } // Response received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { completionHandler(URLSession.ResponseDisposition.allow) DispatchQueue.main.async { [self] in if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode != 200 { DispatchQueue.main.async { [self] in self.myStatus.text = "Error \(String(httpResponse.statusCode))" myBackButt.isEnabled = true } } } } } // Data received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { DispatchQueue.main.async { [self] in
3
0
1.1k
May ’22
Where can I call register(_:forCellReuseIdentifier:) if I am not using a UITableViewController?
Currently I am placing a UITableView inside my UIViewController, with multiple other items. I am not using a UITableViewController. However I am unable to register the identifier "masterlist", or should I say I am not sure where I can register it. I am not using storyboard, and if I am still to register it in my UIViewController's viewDidLoad, I am unable to figure out the proper syntax. Is this something I can do? class BeginNewCustomer: UIViewController { let myList = createTblView() override func viewDidLoad() { super.viewDidLoad() myList.delegate = self myList.dataSource = self } func createTblView() -> UITableView { let myTable = MyTableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0 )) myTable.backgroundColor = .white return myTable } extension BeginNewInv: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dbClass.invsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() // let cell = tableView.dequeueReusableCell(withIdentifier: "masterlist", for: indexPath) var config = cell.defaultContentConfiguration() .... fill the configuration cell.contentConfiguration = config return cell } }
3
0
831
Jul ’22
Do I have to build in support for user scrolling through a UITextView object?
I am trying to add a UITextView within my app to output data to. Naturally the data will eventually be bigger than the size of the UITextView, and the view is a set size. So I would like the user to be able to scroll through its content. However, I cannot scroll through the content in the app. Am I supposed to build the scrolling function myself? Seems weird that I would have to do that, but I cannot seem to find the answer to this on the web. I’ve also noticed that no vertical scroll at shows up when the text count is larger than the size of the object, which makes me wonder if I am missing a property or two. func createStatusField() -> UITextView { let myStatus = UITextView(frame: CGRect(x: 50, y: 50, width: 100, height: 300)) myStatus.autocorrectionType = .no myStatus.text = "hello there" myStatus.backgroundColor = .secondarySystemBackground myStatus.textColor = .secondaryLabel myStatus.font = UIFont.preferredFont(forTextStyle: .body) myStatus.layer.zPosition = 1 myStatus.isScrollEnabled = true myStatus.showsVerticalScrollIndicator = true return myStatus }
3
0
695
Aug ’22
Can a button call a new view without using NavigationStack/Link/View?
Is it possible to switch to a new View without using NavigationStack or NavigationLink or NavigationView? I know I can do it with a Bool, which either shows the second view, or the first, and then toggles the Bool. But can't I do something like this? Which obviously doesn't work. struct BasicButton: View { var buttonLabel = "Create User" var body: some View { Button { CreateUser() //another SwiftUI view, not a function } label: { Text(buttonLabel) } } }
3
0
922
May ’24
Is there a simple way to adding files to iPhone simulator, for use with Xcode?
Correct me if I'm wrong, but with the latest version of Xcode (15.x) you can no longer add files to the iPhone simulator by dragging them into the the Files app. I also tried to share the files from my Mac desktop to the simulator. But after selecting the simulator, absolutely nothing happened. So I had to do it the long way: Add a folder to the simulator with a unique name, in the Files app Get the document path, print(URL.documentsDirectory.path()) Back track into the folder structure till I find that folder cp the files to that folder Please tell me that there is a way that I haven't found on Google, or that I somehow was doing what the Apple dox suggested, but missed a step.
3
3
2.9k
Jun ’24