Retrieve text from UITextField using viewWithTag function - uitextfield

I'm trying to retrieve text from a UITextField that I allow the user to create at runtime. I'm using the following line of code.
let thisTextField:UITextField = self.scrollView.viewWithTag(0) as! UITextField
The compiler error states
Could not cast value of type 'UIScrollView' (0x1032faaf0) to 'UITextField' (0x103318dc0).
I've looked through stackoverflow and the above code appears to have worked with previous versions of Swift but does not appear to work with Swift 2.0.

I have had similar issues with this. Since view tags are non optional it would seem that they are initially set as 0. This means that when it looks for a view with the tag 0 it finds the scrollview and returns that. A couple of solutions would be to set the textField to a value other than 0 or make your textField a class variable.

Related

Scrollview Subviews always 2

I am coming across a strange error. Whenever I call a scrollviews subviews, it always has a count of two, or returns an array of two depending on what I am using.
I have a scrollview with about 20 subviews. I am using the following code to try and retrieve the amount of subviews in that scrollview:
int svCount = svContent.Subviews.Length
Which always returns 2 no matter if I add a new scrollview or try use my existing one. The other code I am trying is as follows:
UIView[] viewArr = svContent.Subviews
Which also returns an array of two subviews. If I try and remove any of those subviews usign RemoveFromSuperview() it does nothing. I tried using the count on my base view as well which also in turn returns 2.
I am using XCode 9.1 and Visual Studio 2017 on Windows 10 x64.
Anyone have a clue about this ? Any ideas would be helpful.

macOS Printing in Swift

Please note this is not an iOS question.
I have an NSView-based app (i.e. not document-based), and I’d like to bolt on a printing subsystem. I can get NSViews in my main controller to print ok. However, I want to have a special view constructed just for printing. The view should not show in the app’s window. The view contains two NSTextFields, two NSTextViews, and 5 labels.
I cannot seem to figure out a way to do this. I have tried various forms of these examples:
Add an NSView to my main view window? Seems logical, but it’s awkward in a storyboard, (I can’t position the view in the storyboard).
Programmatically create a custom NSView with a xib?
For this, I’ve tried:
#IBOutlet weak var printView: NSView!
….
let printOperation = NSPrintOperation(view: printView!)
This results in the comprehensive "fatal error: unexpectedly found nil while unwrapping an Optional value” message.
The outlets are configured correctly (I think)
A seperate ViewController? If so, how can I avoid having two print buttons — one to call the print controller, and the second, to print the PrintController’s view.
I’ve tried reading the Apple docs, but they are not the way I learn best. There are also no Print documents in Swift that I've found. I’ve waded through many SE questions, but have come up blank. Could you point me towards a solution please.
I think the specific problem here is that you're never causing the view to be loaded.
You can double check whether this is the case by overriding the viewDidLoad method on the controller. If it's never called, your view is never loaded from the nib.
Normally the UI machinery takes care of all that when you display a view controller, which is why it can be so confusing when it doesn't happen.
You should be able to trigger the view load by accessing the view property on the controller. e.g.
_ = self.view // Touch the view to force it to load
https://developer.apple.com/documentation/appkit/nsviewcontroller/1434401-view has some additional information.
You can also call loadView() directly although that's usually frowned upon.

What is causing NSNull length unrecognized selector keyCommand error

I have this class/storyboard scene in a project that up to last night worked fine for the past 4 weeks i worked on it.
I have managed to comment out practically everything and I still get the crash when tapping on the UITextField and typing a number. It only crashes when I type in a value, otherwise it doesn't crash.
Here is the class as I am running it now:
import Foundation
import UIKit
import HealthKit
import CoreData
class WorkoutViewController: UITableViewController {
//Properties
#IBOutlet var numberOfLapsTextField: UITextField?
#IBOutlet var metersPerLapTextField: UITextField?
#IBOutlet var workoutDurationTextField: UITextField?
#IBOutlet var paceTextField: UITextField?
var healthStore:HKHealthStore?
override func viewDidLoad() {
super.viewDidLoad()
}
Originally it had the IBOutlets as ! instead of ? And it has a CoreData stack property, some blurred background effects for the tableview background, fetches user's weight from health store on viewDidLoad, a predicate helper method for health store fetches and a cancel and done button. The done button captured data from the textfields, made some computations and saved data to the health store and to coredata. But ALL of this has been commented out leaving only what is seen above.
I did managed to get a weird stack trace in the console one time (can't seem to get it anymore) that read:
[UIPhysicalKeyboardEvent _matchesKeyCommand:]
and a few others like it just before it.
Im stumped, any ideas? Exception breakpoints is one but it just throws me to the AppDelegate class declaration line where UIResponder is adopted. Ive learned and rebuilt. I don't know what else to look for.
Im thinking its a corrupt storyboard file because Ive added and removed scenes with textfields and they all behave the same. Here is my storyboard.xml file:
http://www.santiapps.com/iOS/Main.storyboard.xml
I had a crash with the same cryptic NSNull length message. It cropped up occasionally on only one screen when testing in the simulator and by trial and error I discovered it only happened when I pressed the cmd key.
Looking in my storyboard source I found the following:
<keyCommands>
<keyCommand/>
</keyCommands>
Which I think lets you define keyboard shortcuts for anyone using a bluetooth keyboard. However - this is an empty definition, so it seems pressing cmd caused whatever this executes to fail because I don't have any valid shortcuts defined.
I have absolutely no idea how this happened, but if you use the graphical Interface Builder UI to look at your Storyboard, go to the view controller giving you the problem and click on the root view controller. Under the Attributes inspector there is a Key Commands section. I reckon I must have accidentally hit the + button here at some point. You can select the first 'item' and hit - to get rid of it and the problem should disappear.
Alternatively, delete the keyCommands section from the Storyboard source directly.
I see this question has already been marked as answered, but I include this in case the additional information on top of the original answer (and comment) is useful to someone else.
Ok I deleted the navigation controllers and tab bar controller and re-added them, and the problem is gone! There are no more crashes when I type in data. It was obviously a corrupted scene but the weird thing is that all of a sudden, all scenes with uitextfields got corrupted in the same way.
Click on view controller and in attributes inspector under Key commands remove "Enter action below" entry

Swift subclassing UITextField issues

I've subclassed UITextField and added two variables and a convenience function. One variables holds a String key and the other holds a reference to another TextField which is used to create a custom tab order.
All good except I've run into a small problem. Using the storyboard I'm not able to bind the IBOutlet in the controller to the text field elements that implement this subclass even though they are both the same type. I've had to set the IBOutlet variable to be a UITextField type, bind them and then set the IBOutlet back to the subclass.
This all works in Xcode5 using Objective-C so I assume this is an issue with the beta of XCode6 but just wanted confirm I wasn't missing something.
I am also playing with swift.. I can share what I checked when faced some problems, you can check these. Not sure though it is the solution for your problem.
1. Check class defined for subclass and main class
2. Check delegates defined for text fields.
3. Check if prototyping can solve your problem.
Beta 2 Release of XCode 6 has resolved this issue.

Value binding expects to be bound to a type of NSString

I am building a new app in Xcode 4 and following the bindings tutorial in chapter 6 of Cocoa Programming for Mac OS X, 2nd Edition.
In my XIB, I have dragged in an NSArrayController and placed an NSTableView in my window. The object model class on the array controller is set to URLPrefix and I have defined the prefix key. The URLPrefix model class exists and has a prefix property of type NSString.
When I try to bind a column of the table view to the array controller, no paths are available for autocomplete and a little ! appears on the right side of the text field, informing me that "The Value binding expects to be bound to an object of type NSString, but arrangedObjects is of type URLPrefix."
Hours of searching has yielded nothing, and the Xcode 4 Transition Guide doesn't mention any changes to setting up bindings.
I now believe this is a bug in Xcode 4 and I've filed it with Apple. No answer from them, yet.
While the bindings field doesn't offer the expected auto-complete choices, I can type what I expect anyway and the application compiles and runs correctly.
Edit: Apple responded to me today after being unable to reproduce, and I verified it is no longer a problem in Xcode 4.0.2.

Resources