By default, NSTableView allows the user to clear the rows selection by clicking anywhere in the blank area of the table view. This however is not always intuitive and sometimes isn’t even possible (for example, when the table view doesn’t actually have any empty area inside itself).
So how do you allow the user to deselect the row by simply clicking on it again? No regular delegate methods (like -tableView:shouldSelectRow:) are called in this case so you can’t capture the click on a row that is already selected, this way.
You want to define your own subclass of NSTableView and set up -mouseDown: like so:
- (void)mouseDown:(NSEvent *)theEvent {
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
BOOL wasPreselected = (self.selectedRow == clickedRow);
[super mouseDown:theEvent];
if (wasPreselected)
[self deselectRow:self.selectedRow];
}
Related
When I select a NSTextFieldCell in a NSTableView, the behavior is different depending on the row is selected or not.
If the row is selected the cell is immediately selected, and the cursor is blinking inside the text field
If the row is not selected, the only change after the click is the selection of the row, but the cell doesn't go into edit mode.
I would like to have the cell into edit mode in both cases after 1 click.
Implement this method below, it will edit your cell:-
- (void)editColumn:(NSInteger)columnIndex row:(NSInteger)rowIndex withEvent:(NSEvent *)theEvent select:(BOOL)flag
I think what you want is to edit your cell with one click. For this you need to subclass your tableview and capture its mousedown: event as
- (void)mouseDown:(NSEvent *)theEvent
{
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
NSInteger clickedCol = [self columnAtPoint:localLocation];
[super mouseDown:theEvent];
[self editColumn:clickedCol row:clickedRow withEvent:theEvent select:YES];
}
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).
I have a known location (CGPoint) and I want to query the view (UIView) for the object under it or that contains it, whether its the view itself, or a button inside that, or a label or any other instance
I then want to grab that object, find out it type, and call any methods that happen when its tapped by the user.
I tried calling touchesBegan on the view, but theres no way to create touch events or uievents it seems... correct me if I'm wrong.
I'm thinking there might be a way to do this with hitTest, but I'm unsure.
hit test will do it.
If you don't want something returned, turn off userInteractionEnabled
//Send touch down event
//Now, this is a bit hacky. Theres no public contrustors for UITouch or UIEvent, thus calling touches*: on the view is not possible. Instead, I search the view underneath it (with Hit Test) and call actions on that.
//Note. You need to allow for each type of object below, for the scope of the demo, I've allowed for only UIView and UIButton.
UIView *v = [[self view] hitTest:pointer.frame.origin withEvent:nil]; //origin is top left, point of pointer.
NSLog(#"%#", [v class] );
if([v isKindOfClass:[UIButton class]]){
selectedButton = (UIButton *)v;
}
else if ([v isKindOfClass:[UIView class]] && [[v backgroundColor] isEqual:[UIColor redColor]]){
selectedView = v;
dragLabel.text = #"You are dragging me!";
dragPoint = pointer.frame.origin; //record this point for later.
}
else {
NSLog (#"touched but no button underneath it");
}
I've subclassed the cells of a NSOutlineView, by setting the custom class in interface builder.
I've implemented this delegate method to configure the cells:
- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
Also, I've implemented this method in my custom cell class:
- (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView
which is invoked twice every time I click on the cell. I'm wondering why not just once. The event type is always MouseDown.
I don't know if this matters, but it is invoked twice even if the cell has not parents or children. So it can't be the cells hierarchy.
If I can't rely on hitTestForEvent to trigger an action when a specific area of my cell is clicked, which method should I use ?
Thanks
-hitTestForEvent:inRect:ofView is entirely the wrong method to be using to trigger actions. You should be using -trackMouse:inRect:ofView:untilMouseUp:, or -startTrackingAt:inView:, -continueTracking:at:inView: and -stopTracking:at:inView:mouseIsUp:.
Important Note: If you implement your own mouse tracking loop in -trackMouse:inRect:ofView:untilMouseUp:, you should document this fact somewhere, because generally speaking it will preclude the use of the other three methods. Some of the NSCell subclasses in the AppKit framework do this and fail to document that they have done so (with the result that you’ll ponder for hours why it is that -startTrackingAt:inView: never gets called).
How do you implement your own tracking loop? Like this:
- (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame
ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp
{
NSPoint pos = [controlView convertPoint:[theEvent locationInWindow]
fromView:nil];
if ([theEvent type] == NSLeftMouseDown && NSPointInRect (pos, myClickRect)) {
NSWindow *window = [controlView window];
NSEvent *myEvent;
NSDate *endDate = [NSDate distantFuture];
while ((myEvent = [window nextEventMatchingMask:(NSLeftMouseDragged
|NSLeftMouseUp)
untilDate:endDate
inMode:NSEventTrackingRunLoopMode
dequeue:YES])) {
if ([myEvent type] != NSLeftMouseUp)
continue;
pos = [controlView convertPoint:[theEvent locationInWindow]
fromView:nil];
if (NSPointInRect (pos, myClickRect)) {
// React somehow
}
return YES;
}
}
return [super trackMouse:theEvent inRect:cellFrame ofView:controlView
untilMouseUp:untilMouseUp];
}
(The above code was just typed in here, so the usual caveats apply; it assumes the existence of an NSRect called myClickRect that defines the active area of your cell. You might need to calculate that from cellFrame at the head of the method.)
Obviously you can watch for and handle other events too, if they are relevant to you.
Perhaps I should also add that the three method approach, while conceptually cleaner, tends to be quite a bit slower, which generally leads me to prefer overriding -trackMouse:inRect:ofView:untilMouseUp: as shown above.
How would I use a tableView as a value selector?
So I have a series of input fields and what I want is when you select a cetian field it opens a tableview of options that you can pick from as a value for that field.
Upon selecting an option it returns to the previous View with the selected value filling that field.
This is what I do, similar to the Settings > General > International > Language table view in the iPhone/iPod.
The user can tap a row and a check mark will appear. The view is dismissed when "Done" or "Cancel" is tapped.
First, create a UITableViewController that will display your options. Have a toolbar on the top with a Cancel and Done button. Also have these properties:
SEL selector; // will hold the selector to be invoked when the user taps the Done button
id target; // target for the selector
NSUInteger selectedRow; // hold the last selected row
This view will be presented with the presentModalViewController:animated: method so it appears from the bottom of the screen. You could present it in any other way, but it seems kind of standard across iPhone applications.
Before presenting the view, set target and selector so a method will be called when the user taps the "Done" button.
Now, in your newly created UITableViewController you can implement the thetableView:didSelectRowAtIndexPath:` method as:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark; // show checkmark
[cell setSelected:NO animated:YES]; // deselect row so it doesn't remain selected
cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0]];
cell.accessoryType = UITableViewCellAccessoryNone; // remove check from previously selected row
selectedRow = indexPath.row; // remember the newly selected row
}
Also implement cancel and done methods for the toolbar buttons:
- (IBAction)done:(UIBarButtonItem *)item
{
[target performSelector:selector withObject:[stringArray objectAtIndex:selectedRow]];
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)cancel:(UIBarButtonItem *)item
{
[self dismissModalViewControllerAnimated:YES];
}
You should use UITableViewDelegate's tableView:didSelectRowAtIndexPath:, remember the value somewhere in another object (a share instance/singleton maybe? - depending on your architecture) and then dismiss this table view.
I implemented a ViewController for Date pick.
I create a protocol to return the date picked to the previous view.
#protocol DataViewDelegate
#optional
- (void)dataViewControllerDidFinish:(NSDate*)dateSelected;
#end
...
- (void) viewDidDisappear:(BOOL)animated
{
if ([ (id)(self.delegate) respondsToSelector:#selector(dataViewControllerDidFinish:)])
{
[self.delegate dataViewControllerDidFinish:self.data];
}
[super viewDidDisappear:animated];
}
In the picker view you can use the
tableView:didSelectRowAtIndexPath:
to select the row you want. Here i set the data property.
The previous view is the delegate for the protocol.