Input Accessory View Realization - objective-c

Absolutely beginner obj-c question.
I am totally frustrated last few days about to do my task, but it seems like I have a problem bigger than my level of knowledges now. Before posting this question I asked few times about this in different forms, but so far I haven't understanding of how to do it, so I search for turnkey solution.
Task:
Plain UITableView with two sections. I am interested only in first section to improve Input Accessory View to switch between four textFields in cells.
http://uaimage.com/image/62f08045
Custom cells are inherited from UITableViewCell and have a UITextField's in them as a property. So my task is to set first responder to different textFields.
Ideas:
to set textFields as a delegate for ViewController and then resign and set first responder in input acessory view methods
to tag textFields, set NSMutableArray filled with this textFields and then in -inputAccessoryViewNext and in -inputAccesoryViewPrev change responder
to tag cells by indexPath and get textFields from cell
But I'm unable to realize any of this advances correctly and nothing works for me yet, so very need help.
I'm attached UITableViewController.m and FDTextFieldCell.m (custom cell) above:
https://docs.google.com/open?id=0B5rYA7McNhFlSXBrLTFVU2hVd1U
Will be glad to reward anyone who can help by a modest bounty of reputation.

I think your second idea is the right approach. Add an instance variable to your table view controller like NSMutableArray *_textFields and initialize it in viewDidLoad.
Then, in your tableView:cellForRowAtIndexPath: method, add something like this every time you :
if ([indexPath row] == 0) {
FDTextFieldCell *cell = [self textFieldCell];
[[cell textLabel] setText:#"Ваше Имя"];
[[cell textField] setPlaceholder:#"Обязательно"];
[[cell textField] setText:[profile name]];
[[cell textField] setReturnKeyType:UIReturnKeyNext];
[[cell textField] setKeyboardType:UIKeyboardTypeDefault];
// ADD THIS
[[cell textField] setTag:[indexPath row]];
if (![_textFields containsObject:[cell textField]]) {
[_textFields addObject:[cell textField]];
[_textFields sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"tag" ascending:YES]]];
}
return cell;
}
From there, you have a sorted array of your text fields, so you can implement your accessory methods like so:
- (void) inputAccessoryViewDidSelectNext:(FDInputAccessoryView *)view {
UITextField *textField = nil;
for (textField in _textFields) {
if ([textField isFirstResponder])
break;
}
NSInteger indexOfFirstResponder = [_textFields indexOfObject:textField];
NSInteger nextIndex = indexOfFirstResponder + 1;
if (nextIndex == [_textFields count])
nextIndex = 0;
UITextField *nextField = [_textFields objectAtIndex:nextIndex];
[nextField becomeFirstResponder];
}
- (void) inputAccessoryViewDidSelectPrev:(FDInputAccessoryView *)view {
UITextField *textField = nil;
for (textField in _textFields) {
if ([textField isFirstResponder])
break;
}
NSInteger indexOfFirstResponder = [_textFields indexOfObject:textField];
NSInteger previousIndex = indexOfFirstResponder - 1;
if (previousIndex < 0)
previousIndex = [_textFields count] - 1;
UITextField *previousField = [_textFields objectAtIndex:previousIndex];
[previousField becomeFirstResponder];
}

Related

NSScrollView displaying problems in Xcode 5 after scrolling

NSScrollView displaying NSTableView based on custom view (Image, checkbox and text label). When I scroll - I have lag (bug?) with redrawing rows.
Normal:
Bugged after scroll:
Project (and .xib file) was updated from Xcode 4 to Xcode 5 format. I think this bug appeared after it, but I'm not sure.
Any suggestions how to fix it?
Realisation of NSTableViewDataSource, NSTableViewDelegate protocols:
- (NSInteger) numberOfRowsInTableView: (NSTableView *) aTableView {
return [arrayOfObjects count];
}
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
CMListItem *currentObject = [arrayOfObjects objectAtIndex: row];
NSString *currentName = [currentObject name];
BOOL currentState = [currentObject state];
NSImage *currentImage = [currentObject getArtwork];
NSString *identifier = [tableColumn identifier];
if ([identifier isEqualToString:#"MainCell"]) {
CMTableCellView *cellView = [tableView makeViewWithIdentifier: identifier owner: self];
cellView.textField.stringValue = currentName;
cellView.button.state = currentState;
cellView.imageView.image = currentImage;
return cellView;
}
return nil;
}
NSScrollView not modified.
My own table cell view - subclass of NSTableCellView with few additional outlets.
UPDATE: this thing helped me: set Can Draw Concurrently for all NSTableView at On state, then turn it to Off state.
I think I have seen this problem sometimes when "Copy On Scroll" is enabled. Try disabling this option in IB (in the attribute inspector, scrollview section, behavior).

UITableView is lagging a cell containing a UITextView is displayed the first time

I'm running into issues with a UITableView that lags while scrolling when specific cells will move to superview.
I've written my own IPFormKit for an easy way to create beautiful input forms with different kind of inputViews without having to re-code everything manually for each form field / cell.
I've got a UITableViewController that initializes my IPFormKit and its fields.
The - (UITableViewCell *) cellForRowAtIndexPath:(NSIndexPath)indexPath; loads the dequeued custom cells (called IPFormTableViewCell) and assigns the IPFormField to each cell.
The custom UITableViewCell (IPFormTableViewCell) creates all (possibly) required inputViews (UITextField, UITextView, CustomUILabel) with a CGRectZero on initialization.
The matching inputView depending on the IPFormField's type (that was already inited as an iVar of the cell) is resized and added as a subview to the cell.contentView within.
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath)indexPath
For UITextField and CustomUILabel this works flawlessly, but when the inputView is a UITextView, the scrolling of the UITableView lags (slightly) noticable when this cell will be displayed for the first time.
When the cell will be displayed again later after scrolling a bit (even if the cell was reused and thus the UITextView removed and readded), there is no lag and scrolling is super smooth for those cells.
I'm running out of ideas what the reason for this lag could be.
Any idea is appreciated.
PS: The lag is noticable on both, iPhone 4 and iPhone 4S and is of almost exactly the same duration (so it should not be CPU related)
UITableViewController.m:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"IPFormFieldCell";
// Get Form Field for indexPath
IPFormField *formField = [self.form fieldAtIndexPath:indexPath];
IPTableViewCell *cell = (IPTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[IPTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.backgroundView = nil;
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
cell.selectedBackgroundView = nil;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell assignFormField:formField];
return cell;
}
IPFormTableViewCell.m:
- (void) assignFormField:(IPFormField *)field:
- (void) assignFormField:(IPFormField *)field {
if (formField != nil) {
formField.inputView = nil; // unlink old field
}
self.formField = field;
// Change Field Label
[fieldLabel setText:[field label]];
// Add an Input View to the Field
UIView *labelView = nil;
UIView *inputView = nil;
switch (formField.type) {
case IPFormFieldTypeTextField:
{
labelView = fieldLabel;
UITextField *textField = inputTextField;
textField.delegate = (IPFormTextField *)formField;
textField.inputAccessoryView = [formField.form inputAccessoryView];
textField.placeholder = [self.formField stringFromValue:self.formField.defaultValue];
textField.keyboardType = [(IPFormTextField *)formField keyboardType];
if (self.formField.value == nil || [[self.formField stringFromValue:self.formField.value] isEqualToString:[self.formField stringFromValue:self.formField.defaultValue]]) {
textField.clearsOnBeginEditing = YES;
} else {
textField.text = [self.formField stringFromValue:self.formField.value];
textField.clearsOnBeginEditing = NO;
}
inputView = textField;
break;
}
case IPFormFieldTypeTextArea:
{
UITextView *textView = inputTextView;
textView.delegate = (IPFormTextArea *)formField;
textView.inputAccessoryView = [formField.form inputAccessoryView];
if (self.formField.value == nil || ![[self.formField stringFromValue:self.formField.value] length] > 0) {
textView.text = [self.formField stringFromValue:self.formField.defaultValue];
} else {
textView.text = [self.formField stringFromValue:self.formField.value];
}
inputView = textView;
break;
}
default:
break;
}
self.leftItem = labelView;
self.rightItem = inputView;
if (leftItem != nil) {
[self.contentView addSubview:leftItem];
}
if (rightItem != nil) {
[self.contentView addSubview:rightItem];
}
formField.inputView = rightItem;
}
Apparently, cellForRowAtIndexPath: of my dataSource made use of a field's property, that was set as #property (nonatomic, copy) instead of #property (nonatomic, readonly).
Now that I've fixed it, the scrolling isn't lagging anymore.
As I guessed, your problem here is with your custom controls. Yes, you are reusing the cell, but this doesn't give anything in your case, as every time you request for the cell, you are creating new custom control for each cell. My advise, you can create and keep your custom controls as an instance variables, and when required return them without many if-elses, or, you could create custom cells for your two cases, and keep them dequeued with different cell identifiers and reuse them. Good Luck!

Multiple UITextFields in a custom UITableViewCell

I have a UITableView that has 2 different customcell definitions. One is a single UITextField and the other has 4 UITextFields
userInteractionEnabled is manually set to enable cell level touch navigation, and I handle the UI interaction within didSelectRowAtIndexPath to the first responder to the relevant cell
This all worked fine when I was using just the one customcell (EditableCustomCell) with one UITextField (editableTextField), but now I have a customcell (LatLonCustomCell) with 4 UITextFields (degrees, minutes, seconds, cartesian), I cannot determine which field has been touched in order to set becomeFirstResponder
(currently I'm defaulting in the first textfield called degrees during debug)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[prevField resignFirstResponder];
prevField.userInteractionEnabled = NO;
if(indexPath.section == kFirstSection && (indexPath.row == kLatitudeRow || indexPath.row == kLongitudeRow)) {
LatLonCustomCell *customCell = (LatLonCustomCell *)[MyTableView cellForRowAtIndexPath:indexPath];
currField = customCell.degrees; // need to set correct field here
} else {
EditableCustomCell *customCell = (EditableCustomCell *)[MyTableView cellForRowAtIndexPath:indexPath];
currField = customCell.editableTextField;
}
currFieldIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
currField.userInteractionEnabled = YES;
[currField becomeFirstResponder];
}
OK, so for those that come across this with the same or similar problem, I have finally made a breakthrough
I decided that I was going to need to capture the X/Y coordinates of the touch prior to the didSelectRowAtIndexPath being called. This way I could then determine which UITextField the touch occurred in by checking the touch against the "bounds" of the textfield
After some random searching, I found that a VERY easy way of capturing ANY touch event in the viewcontroller (as touchesBegan only occurred in the custom overridden UITableViewCell class and I knew not how to pass this back up the chain Cell > TableView > Scroll View > Controller)
By adding this to the viewDidLoad method:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 1;
// Pass the tap through to the UITableView
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];
This captures all touches, calling the handleTapGesture method
Then within this method it was simply a case of checking if the touch was within the bounds of the tableview, and if so, determine the indexPath for the point touched and then check against the bounds of the object required, below is a simplified version of what I came up with
-(void)handleTapGesture:(UITapGestureRecognizer *)tapGesture {
CGPoint tapLoc = [tapGesture locationInView:self.tableView];
if([MyTableView indexPathForRowAtPoint:tapLoc]) {
// Tap still handled by the UITableView delegate method
NSIndexPath *indexPath = [MyTableView indexPathForRowAtPoint:tapLoc];
if(indexPath.section == 0 && (indexPath.row == kLatitudeRow || indexPath.row == kLongitudeRow)) {
LatLonCustomCell *customCell = (LatLonCustomCell *)[MyTableView cellForRowAtIndexPath:indexPath];
UIScrollView *scrollView = (UIScrollView *)self.view;
CGRect rc;
// Degrees
rc = [customCell.degrees convertRect:[customCell.degrees bounds] toView:scrollView];
if (tapLoc.x >= rc.origin.x && tapLoc.y >= rc.origin.y && tapLoc.x <= (rc.origin.x + rc.size.width) && tapLoc.y <= (rc.origin.y + rc.size.height)) {
NSLog(#"touch within bounds for DEGREES");
touchField = customCell.degrees;
}
// Repeat for other textfields here ....
....
In my code I save the field within touchField, as within the didSelectRowAtIndexPath code, I am already handling prevField/currField values to control the enabling/disabling of userInteractionEnabled and to set the currField as becomeFirstReponder
Hope this proves helpful to someone :)
In the past when I have needed to check if a text box has been touched I checked if YourTextField.text.length > 0. If it is you can set becomeFirstResponder. Hope this helps.
Have you thought about using NSNotificationCenter to request notifications for UITextFieldTextDidBeginEditingNotification?
in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(textFieldBeganEditing)
name:UITextFieldTextDidBeginEditingNotification object:nil];
and then something like
-(void) textFieldBegainEditing: (NSNotification*) notification {
// [notification object] will be the UITextField
// do what you need to do with it (resign, become first responder)
}

Clickable Text with Hover Effect in NSTableView

I'm trying to create a column of clickable URL-type text (NOT URLs like this, but essentially a borderless, title button or text field cell with a tracking area for a hover effect) within an NSTableView.
1.) When the user hovers over a particular cell the text in that cell should draw an underline below the text (hover/trackable area effect).
2.) When the user clicks the text it should perform an action.
I've subclassed NSCell and NSTableView and added a tracking area within the custom tableview to try and track the mouse location of the individual cell of the table to notify the cell when to redraw itself. I can get the current row and column of the mouse location, but can't seem to get the right cell in my custom tableview's mouseMoved: method
-(void)mouseMoved:(NSEvent *)theEvent {
[super mouseMoved:theEvent];
NSPoint p = [self convertPoint:[theEvent locationInWindow] fromView:nil];
long column = [self columnAtPoint:p];
long row = [self rowAtPoint:p];
id cell = [[self.tableColumns objectAtIndex:column] dataCellForRow:row];
}
It gets the cell for the column, but doesn't get the right cell for that particular row. Perhaps I'm not fully understanding the dataCellForRow: function for NSTableColumn?
I know you can't quite add a tracking area for cells, but instead you must create the hit test for mouse clicks and then begin tracking once the hit test is successful (meaning the mouse is already down) and then use startTracking:, continueTracking:, and stopTracking: to get the mouse's position. The idea though is that it has a hover effect before any mouseDown: action.
Also, I can't just use a view-based tableview (which would be incredible) because my app must be 10.6 compatible.
I'm not sure what's wrong with your method of getting the cell, but you don't really need to get that to do what you want. I tested a way to do this that entailed creating a table view subclass to do the tracking in the mouse moved method. Here is the code for that subclass:
-(void)awakeFromNib {
NSTrackingArea *tracker = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveInActiveApp owner:self userInfo:nil];
[self addTrackingArea:tracker];
self.rowNum = -1;
}
-(void)mouseMoved:(NSEvent *)theEvent {
NSPoint p = theEvent.locationInWindow;
NSPoint tablePoint = [self convertPoint:p fromView:nil];
NSInteger newRowNum = [self rowAtPoint:tablePoint];
NSInteger newColNum = [self columnAtPoint:tablePoint];
if (newColNum != self.colNum || newRowNum != self.rowNum) {
self.rowNum = newRowNum;
self.colNum = newColNum;
[self reloadData];
}
}
-(void)mouseEntered:(NSEvent *)theEvent {
[self reloadData];
}
-(void)mouseExited:(NSEvent *)theEvent {
self.rowNum = -1;
[self reloadData];
}
I put the array and table delegate and data source code in the app delegate (probably not the best place, but ok for testing).
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.theData = #[#{#"name":#"Tom",#"age":#"47"},#{#"name":#"Dick",#"age":#"21"},#{#"name":#"Harry",#"age":#"27"}];
[self.table reloadData];
self.dict = [NSDictionary dictionaryWithObjectsAndKeys:#2,NSUnderlineStyleAttributeName,[NSColor redColor],NSForegroundColorAttributeName,nil];
}
- (NSInteger)numberOfRowsInTableView:(RDTableView *)aTableView {
return self.theData.count;
}
- (id)tableView:(RDTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
if (self.table.colNum == 0 && rowIndex == self.table.rowNum && [aTableColumn.identifier isEqualToString:#"Link"]) {
NSString *theName = [[self.theData objectAtIndex:rowIndex] valueForKey:#"name"];
return [[NSAttributedString alloc] initWithString:theName attributes:self.dict];
}else if ([aTableColumn.identifier isEqualToString:#"Link"]){
return [[self.theData objectAtIndex:rowIndex] valueForKey:#"name"];
}else{
return [[self.theData objectAtIndex:rowIndex] valueForKey:#"age"];
}
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
if (self.table.colNum == 0)
NSLog(#"%ld",[aNotification.object selectedRow]);
}
I use the delegate method tableViewSelectionDidChange: to implement the action if you click on a cell in the first column (which has the identifier "Link" set in IB).

Is Empty selection in an NSTableView with Source List Highlighting not allowed?

I feel like I may be missing something obvious here, but if I have an NSTableView with it's Highlight set to Source List and with Empty selection enabled, I don't seem to be able to click on a blank row in the table to clear the selection.
Changing the Highlight to regular fixes the problem, but of course doesn't draw in the manner I'd like.
The table has no bindings and uses a custom data source. Is there a way to work around this limitation?
For now, I've ended up adding the following to my NSTableView subclass:
- (void)mouseDown:(NSEvent *)theEvent
{
[super mouseDown:theEvent];
if ( [self allowsEmptySelection] && [self selectionHighlightStyle] == NSTableViewSelectionHighlightStyleSourceList )
{
NSInteger row = [self rowAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if ( row == -1 )
{
[self deselectAll:nil];
}
}
}
You can use target actions to accomplish this. During initialization do the following:
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.target = self;
self.tableView.action = #selector(singleClickAction:);
self.tableView.allowsEmptySelection = YES;
Then add a method to your class:
- (void)singleClickAction:(id)sender
{
NSInteger clickedRow = [sender clickedRow];
if (clickedRow < 0) {
[self.tableView deselectAll:self];
}
}