Objective-C, Set UITextField Value from this: - objective-c

I have been told that to access a UITextField in the setup i have with my app, i have to use a subView whatever this is (in a noob at objectivec) and i was given this
[subview isKindOfClass:[UITextField class]]
Where do i put this? And how can i use it to set the value of my UITextField? :D
Thanks!
Update: I want to set the value of my textfield, in the function that is called after my URLScheme - the scheme bit works as i have alerted out the url.. this is cool, now i need to set a textfield with a string?

Iterating through subviews and choosing based on type is not generally considered good design practice. You should reconsider how this is structured to have explicit access to the UITextField you want to access. Doing this with Apple's private classes in particular will deny you access to the App Store. At any rate, here's how you'd do what you want:
for(UIView *subview in myParentView){
if([subview isKindOfClass:[UITextField class]])
[(UITextField *)subview setText:#"MyString"];
}

This is still very little useful context, but you most likely want to create an outlet to your text field and just set the value using that reference (with the text property).

Related

Getting objects from a window Cocoa

What's the best way to get objects from a window. I have a sudoku-like grid of 81 NSTextFields and I would prefer to simply have an array of NSTextFields instead of 81 individual NSTextFields linked through IBOutlets.
For example: if there was a way to send a message to NSWindow such as getObject: (NSString*) title and then use a for-loop to add these NSTextFields to an NSMutableArray, that would be ideal. Any suggestions would be appreciated!
-Luke
You could do the following:
NSArray *subviews = [_window subViews];
for(NSView *subview in subviews)
{
if( [subview isKindOfClass:[NSTextField class]] )
{
[_textFields addObject:subview];
}
}
in -awakeFromNib
Now for the nagging, I don't think you should do it this way. Creating a custom NSView to act as a "Sudoku" view would be both easier to use in your code and better for performance of your application. Loading the Window with 81 textFields is quite heavy + uses a lot more memory.
It sounds to me like you would be much better off with an NSMatrix of NSTextFieldCells.
A matrix is a single object that you can reference with a single outlet connection (or other property), and it knows about rows and columns (so no need to convert those to and from linear indexes). You can also access its individual cells to configure them separately; for example, to set the filled-in values and disable those cells so the user can't change them.

Longpress On UI Element (Or How To Determine Which Element Is Pressed?)

I have an app that has a rather large help section in PDF form. It's getting to me that the PDF is so large and I can tell in instruments that it's putting a little too much strain on the processor, so I'm going to phase it out.
I figured, a lighter implementation would be using a UILongPressGestureRecognizer that I could attach to every UI element that would display specified text in maybe a popover or a UIMenuController indicating the function of the selected element.
So my question is this: How can I attach something like a tag to EVERY element in the view so it can be passed to a single method? When I tried tags, I found there was no way to access it through the (id)sender section of my method signature and thus there was no way to differentiate between the elements.
EDIT: to the person below: While you have solved my facepalm of a question as to determining the tags of views, how might one go about attaching gesture recognizers to a UIBarButtonItem so as to ascertain it's tag? Your implementations allow for a very nasty unrecognized selector because UIGestureRecognizers dont have a tag property.
You can derive the tag from an object passed in as the sender. Just have to check it's class and cast it appropriately. tag is a UIView property so we'll start there.
- (void)someMethod:(id)sender
{
if (![sender isKindOfClass:[UIView class]])
return;
UIView *senderView = (UIView *)sender;
NSInteger tag = senderView.tag;
}
You can access tags through the -(IBAction)xxxxxx:(id)sender; like so:
NSInteger tagValue = [sender tag];
But why can't you just connect the actions to your elements through Interface Builder?
What are the UI elements your using here?

Descendant as an parent's delegate

Lets say I want to create my own text view with maximum characters constrain. And I want to do that constrain in level below - in text view.
I think of creating CustomTextView : UITextView where customTextView.delegate would be the same object - customTextView (self.delegate = self). The definition of the class would be CustomTextView : UITextView <UITextVIewDelegate> and I would implement – textView:shouldChangeTextInRange:replacementText: to do the constrain logic in.
But somehow this do not work. Can I get explanation why or what can be wrong and how to achieve my intent?
If you are subclassing UITextView, why would you need to set itself as the delegate? The delegate is only used to notify code outside of the UITextView that something changed in the UITextView. This means that the UITextView is notified of changes to itself first and, using the delegate, you can notify external code (UIViewController, etc.) of what happened. If you are subclassing the UITextView, it should receive those change notifications from the OS.
However, looking through the documentation, I cannot see how you would track the built-in events by subclass alone. Here's an article I found with a Google search: Subclassing a UITextView

Cocoa auto-update dictionary values from NSTextField

Right now I have a dictionary containing a string value and an NSTextField in my interface. However, in order to update this value I have to click a button that then runs the update code. How can I make it dynamically update anytime the text field's value changes?
Look into using Cocoa Bindings.
They're designed to keep your view (NSTextField) in sync with your model (dictionary) without writing all the glue code in between. They're a bit tricky to learn, but once you understand them, they're super useful.
In your case, you'd bind the "value" binding of the NSTextField to a property in your code.
An alternative is to set up an NSTextFieldDelegate and implement:
- (void)controlTextDidChange:(NSNotification *)aNotification
to modify the value in the dictionary. For example,
- (void)controlTextDidChange:(NSNotification *)aNotification {
[myDictionary setValue:[myTextField stringValue] forKey:#"MYDictionaryKey"];
}
Now whenever the user modifies the text in the NSTextField, the text field will fire this callback to its delegate. This way, you can make sure the dictionary always has the same value as what's displayed on screen.
If you only want the changes to take effect when the user is done editing, you'd implement:
- (void)controlTextDidEndEditing:(NSNotification *)aNotification

Is it possible to design NSCell subclasses in Interface Builder?

I'm trying to subclass NSCell for use in a NSTableView. The cell I want to create is fairly complicated so it would be very useful if I could design it in Interface Builder and then load the NSCell from a nib.
Is this possible? How do I do it?
The question was about a subclass of NSCell; the other answers seem to be doing something else, likely taking advantage of UITableViewCell being a view.
NSCell is not a view. While laying a custom cell out in IB would be a useful thing to be able to do, I think the answer is basically "no, this is not possible". When you subclass NSCell, you're pretty much just doing your own drawing. There isn't support subcells, or parameterized auto layout (ala NSView's springs and struts), which is I suspect what you're looking for.
The only caveat is that you could design an NSCell subclass that did do layout of sub-elements and provided parameters for setting those subelements and all tweakable parameters. Then, you would need to write an IB plugin to make that cell and accompanying inspector available at design time in IB.
This, however, is probably harder than writing a little custom app that does more or less the same thing. Put an NSCell in a control in the middle of a window, and make yourself UI for tweaking the parameters you're interested in. Bindings can make this pretty straightforward for positioning stuff (i.e. bind an x value to a slider), though you will not get direct manipulation of the elements of course. When you're done, you could archive your cell and load the archive at runtime in your real app, or you could just log out the properties and set them in code in your app.
Some answers in this thread have gone off topic because they're talking about Cocoa Touch, when the original question was about Cocoa - the 2 APIs are quite different in this regard and Cocoa Touch makes it easy because UITableViewCell is a view subclass. NSCell isn't, and that's the problem
For information, I had to do something very similar in NSOutlineView recently - which is basically the same, but a little harder if anything because you have to deal with disclosure / collapse of levels. If you're interested in the code, I posted about it here: http://www.stevestreeting.com/2010/08/08/cocoa-tip-using-custom-table-outline-cells-designed-in-ib/
HTH
As Ken says, NSCells and NSViews are different, and you can only lay out NSView hierarchies in NIB, not NSCells (which don't have any explicit hierarchy).
On the other hand, there's nothing preventing you from having a hierarchy of NSViews and using that to draw your NSCell -- you could add them as a subview of your cell's parent view, tell them to display, and remove them from the window and nobody would be the wiser.
In this case, using a NIB would work, although it seems like a ton of hassle. Typically I've just replaced the object that takes NSCells with a custom one that takes my NSViews, but that means writing your own mouse-handling code, which is very touchy.
On the other hand, my approach lets you bind the views' values in NIB, so you don't have to do any extra work, which is cool.
In IB, start an empty XIB. Now go to the pallete and drag in a UITableViewCell, double click to bring up and edit.
include only the custom UITableViewCell (no other UIViews or other top level controls) - make sure it's a real UITableViewCell in IB, or you cannot set a reuse identifier (as opposed to casting a UIView in IB as your custom UITableViewCell class).
Then you can add lables or whatever you like within the cell, as well as setting the reuse identifier or set whatever disclosure indicator you might like.
To use, you provide code like this in the tableView:cellForRow:atIndexPath: method:
YourCustomCellClass *cell = (YourCustomCellClass *)[tableView dequeueReusableCellWithIdentifier:<IDYouSetInXIBFile>];
if ( cell == nil )
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:<YourXIBName> owner:self options:nil];
id firstObject = [topLevelObjects objectAtIndex:0];
if ( [ firstObject isKindOfClass:[UITableViewCell class]] )
cell = firstObject;
else cell = [topLevelObjects objectAtIndex:1];
}
If you have any labels or other controls you want to reference in your code, wire them in IB to your custom cell class - NOT the file's owner, which you do not ever need to set using the above code (you can leave it as NSObject).
Edit: I note you are really looking for an NSCell answer, but the code approach to using IB should be identical in Cocoa with the Cocoa Touch code I used above as loadNibNamed is a standard Cocoa call.
Joar Wingfors wrote an article for Stepwise a few years back on a related topic, Subviews in TableView Rows.
The principal technique is to create an NSCell that can host an NSView. If you were to do this, you could then design an NSView subclass in Interface Builder that you could embed anywhere you need that specific cell.
Another possibility, if you can target Leopard, is to see whether you need to use an NSTableView or whether you can use an NSCollectionView. Collection views deal directly in terms of "item views" rather than in cells, so they're much more straightforward to design in Interface Builder.
I found some interesting examples which I do not totally understand, though.
GitX extends the NSTextFieldCell in their PBIconAndTextCell, referencing this post.
WWDC 2009 - Session 110 "Presenting User Data with Table Views and Browsers" talks "Adding subviews" and "Custom cell editors". (I do not have the source code, though.)
Display an NSTextfieldCell containing text and an image within a NSTableView, #70
Display an NSTextfieldCell containing text and an image within a NSTableView, #71
The last 2 examples work with NSTableViewDataSource and NSTableViewDelegate. I would like to use Bindings an ArrayController in the InterfaceBuilder to connect other UI elements like text fields.
I stumbled into another discussion where Abizern points out PXListView by Alex Rozanski which looks very promising!
I am trying to implement a solution for the problem myself. Please find my project on github and the latest rendering problems over here.
I do it like this:
/* example of a silly way to load a UITableViewCell from a standalone nib */
+ (CEntryTableViewCell *)cell
{
// TODO -- this is really silly.
NSArray *theObjects = [[NSBundle mainBundle] loadNibNamed:#"EntryTableViewCell" owner:self options:NULL];
for (id theObject in theObjects)
if ([theObject isKindOfClass:self])
return(theObject);
NSAssert(NO, #"Could not find object of class CEntryTableViewCell in nib");
return(NULL);
}
However it isn't very efficient and if you're loading lot of data it might hurt you. Of course you should be using a reuseIdentifier which should force this code to only run a handful of times per table.
1) Create NSViewController TableViewCell.h
2) Create in TableViewCell.h some procedures like
-(void)setText:(NSString *)text image:(NSImage *)image
3) In Main class #import "TableViewCell.h"
4) In Main class in -(NSView *)tableView:viewForTableColumn:row: write:
NSImage *img = //some image
TableViewCell *cell = [[TableViewCell alloc] initWithWindowNibName:#"TableViewCell"];
cell.view.init;
[cell setText:#"some text" image:img];
return cell;
Hope this will help =)
I want to provide a more modern approach here.
Starting with iOS 5, UITableView has a method
(void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
Once you registered your NIB containing your cell, just use
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
to get a new cell. If a cell is available for reuse, it will be returned, otherwise a new cell is automatically created, and in that case this means loaded from the NIB file.
Add your UITableViewCell to your tableviewcontroller and declare an IBOutlet property:
#interface KuguTableViewController : UITableViewController {
IBOutlet UITableViewCell *customTypeCell;
}
#property (readonly) UITableViewCell *customTypeCell;
... then in cellForRowAtIndexPath you can just use your cell and set it to be reused:
static NSString *CellIdentifier = #"CustomCell"
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = customTypeCell;
cell.reuseIdentifier = CellIdentifier;