I am trying to setup a NSTableView with a custom cell using an ArrayController and Bindings. To accomplish this I added a subview to the custom cell. The data connection seems to work somewhat. Though, there seems to be a redraw problem which I cannot fix. When I load the application only some of the cells are rendered. When I scroll through the rows or select one the rendering changes.
I created an example project on github to illustrate what the problem is.
The actual source code for the cell rendering can be found here:
// CustomCell.m
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
if (![m_view superview]) {
[controlView addSubview:m_view];
}
// The array controller only gets wrapped data items pack by the NSObjectTransformer.
// Therefore, objectValue returns a NSObjectWrapper.
// Unpack the wrapper to retreive the data item.
DataItem* dataItem = [(NSObjectWrapper*)[self objectValue] original];
[[m_view name] setStringValue:dataItem.name];
[[m_view occupation] setStringValue:dataItem.occupation];
[m_view setFrame:cellFrame];
}
It seems as if the parent controlView does not redraw. Can I force it somehow?
This is almost certainly not a best practice way of doing this, and I'll explain why afterwards: however, it does seem to work. Replace your cell class's drawInteriorWithFrame:inView: method with the following:
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
DataItem* dataItem = [(NSObjectWrapper*)[self objectValue] original];
[[m_view name] setStringValue:dataItem.name];
[[m_view occupation] setStringValue:dataItem.occupation];
[m_view setFrame:cellFrame];
NSData *d = [m_view dataWithPDFInsideRect:[m_view bounds]];
NSImage *i = [[NSImage alloc] initWithData:d];
[i setFlipped:YES];
[i drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
}
The problem is that only one NSCell is created for the entire table. That's how cells are meant to work: the table view creates a cell, and calls setObject… followed by drawInterior… over and over again to get the cell to draw the whole table. That's great from an efficiency perspective (the NSCell class was designed back when 25mhz was a fast computer, so it aimed to minimise the number of object allocations), but causes problems here.
In your code, you populate a view with values, and set its frame, adding it as a subview of the table view if needed. However, since you've only got one instance of NSCell, there can only be one view: you took the single view that you had and merely moved it down the rows of the table.
To do this properly, you'd need some data structure to track all the views you added as subviews of your NSTableView, and when the cell is updating one in the drawInterior… method you'd need to look up which the correct one was and update that. You'd also need to allocate all these views in code (or at least move the view to a separate nib which you could load multiple copies of), because as it is you've only got one in your nib and copying a view is a pain.
The code I wrote is a kludge, since it's really inefficient. What I did was each time the view needs to draw, I drew the view into an off screen image buffer, and then drew the buffer into the correct place in the table view. In doing so, I avoided the problem of only having one view, since the code just takes and draws a new copy of its contents whenever it is needed.
EDIT: See my other answer for explanation
Have you implemented copyWithZone:? You'll need to ensure you either copy or recreate your view in that method, otherwise different cells will end up sharing a view (because NSTableView copies its cells).
Related
I have a basic UITableView that contains 20 cells, one of the cells is a MKMapView just dropped in as is without any custom code (not even setRegion:Animated), if I open the view at the first time and scroll down the table view (towards the map's cell), there is a noticeable hang happens for the app, and if I use setRegion:Animated (without dropping any pin) the hang gets longer. However, this block of the main thread disappears on later attempts to scroll towards the map's cell.
I can't use the MKSnapShotter because I want the user to interact with the map so an image won't satisfy the case.
the table view does not make any block on the main thread if the map does not exist.
how to avoid blocking the main thread while showing the map's cell for the first time ?
First make a tableView IB outlet if you haven't already done so. Create the cell in view did load using tableView.dequeueReusableCellWithIdentifier("mapCellIdentifier") and store that in an ivar. Then in the data source return the cell when the index path is the one you want so inside of cellForRowAtIndexPath do
if (indexPath.row == wantedRow) {
return mapCell
}
The mapCellIdentifier needs to be set in the cell you created in interface builder for the map. This is assuming you have dynamic cells.
I have a custom UITableViewCell to implement swiping horizontally with UIAttachmentBehavior and a UIPanGestureRecognizer. Here's the relevant portion, in the UITableViewCell subclass:
- (void)panDidChange:(UIPanGestureRecognizer *)gesture {
CGPoint location = [gesture locationInView:[self tableView]];
location.y = CGRectGetMidY(self.frame);
switch (gesture.state) {
case UIGestureRecognizerStateBegan: {
self.panAttachment = [[UIAttachmentBehavior alloc] initWithItem:self attachedToAnchor:location];
[self.animator addBehavior:self.panAttachment];
break;
}
Then, when UIGestureRecognizerStateChanged, I just set the self.panAttachment.anchorPoint as the location.
Now, this works fine from startup, but as soon as I add a cell to the tableView or delete a cell from the tableView and try to swipe, the cell moves to it's previous position before the tableView change (one cell down if a cell was deleted, one cell up if a cell was added). As far, as I can tell, this is because the cell's frame isn't being updated when it's position in the tableView changes, so location's y coordinate is out of sync. I've tried [self setNeedsDisplay] and all other "Update view" methods I could find, to no avail.
I am creating the animator referenced above like so:
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:[self tableView]];
It looks like the issue is in a couple different places:
Your animator is being initialized with your entire table view as the reference view.
You are then creating the attachment behavior with an anchor of midY in the tableView's coordinate system, meaning your attachment behavior is now anchored to a point in the tableView's reference coordinate system that is wherever the center point of the cell is located. I bet if you tried to scroll your tableView, weird things would also happen.
Depending on what your goal is for your dynamics behavior, you need to modify both your animator's reference frame and attachment's anchor point in order to fully define what physics simulation you are trying to achieve. Based on the above, it looks like you are trying to simply move the entire cell on the pan. I would recommend that you try moving only a specific container view inside your view hierarchy instead since the table view is going to be placing your cells directly using frames.
If you are looking to provide a pan with a snap-back effect on cancel, then this effect might be better implemented using a couple of UIAttachmentBehavior instances. One behavior instance to anchor the view you are wanting to swipe to it's resting position, and one to actually perform the panning and move the view like you are doing above during the pan. You can tweak the interaction between the two interactions by changing the damping and frequency. This question is a good reference for dragging in general using dynamic items.
In summary to fix your current issue:
Define your animator's reference bounds to the cell's coordinate system, preferably using cell.contentView
Have your cell manage the animator directly since the animator should only be concerned with a view in it's coordinate system. Your animator should have no knowledge of the table view's view hierarchy. Add/remove UIDynamicBehavior items from your cell's animator.
I'm trying to make a rotation on a tableview to tilt the table (to give the effect of a 3d text crawl similar to the star wars opening crawl).
After looking around I found this question objective-с CALayer UIView real rotation
and the accepted answer seems to do what I want, however when I apply the code to my TableView it does nothing and the table appears as usual.
This is the code I am copying:
float distance = 50;
CATransform3D basicTrans = CATransform3DIdentity;
basicTrans.m34 = 1.0 / -distance;
_tableView.layer.transform = CATransform3DRotate(basicTrans, M_PI_4, 1.0f, 0.0f, 0.0f);
I'm placing this in my viewDidLoad method after creating my array of Strings (that populate the tableView)
I currently only have three other methods in the Controller:
didReceiveMemoryWarning (automatically addd when project created)
tableView: numberOfRowsInSelection (used for setting up the table view)
tableView: cellForRowAtIndexPath (used for setting up the table view and setting the cells text form the array)
My understanding is that the tableview has a CALayer, and that the CATransform3D manipulates this to give the representation of the view in a 3d space. If my understanding is correct then I don't get why the list is shown normally on screen? I appreciate the numbers my not give the effect I want yet but they should at lest effect the appearance of the tableView on screen.
Also I have imported QuartzCore etc and added it in linked frameworks
Solution is to use the code marked as OLD answer in the the - (UITableViewCell *)tableView: cellForRowAtIndexPath: method after the cell is checked for being null.
Since the approach suggested below has not worked, another thing I would try out is applying the transform to the UITableView's subviews. Actually, UITableView is a UIScrollView, so it is just a container for subviews that make up the real content of the table view. I would try something like this:
for (UIView* subview in tableView.subviews) {
subview.layer.transform = ...;
}
I have never inspected a table view subviews hierarchy, so I cannot say whether this will work or you should rather apply the transform to just one of the subviews, but I hope this can lead you in the right direction.
OLD ANSWER:
You could try setting your table view's layer sublayerTransform instead of `transform':
You typically use this property to add perspective and other viewing effects to embedded layers. You add perspective by setting the sublayer transform to the desired projection matrix. The default value of this property is the identity transform.
(source).
I am suggesting this based on the hypothesis that a UITableView has quite a complex structure in terms of subviews, so transforming just the view's layer might have no effect. I haven't tried it, though, so I cannot guarantee it will work.
Has anyone ever had experience embedding a field editor (for a NSTextField) inside a scroll view? I'm trying to make the NSTextField scrollable while editing.
Things I've tried:
Dynamically embed it when the custom field editor's -becomeFirstResponder gets called. This semi works; the problem is that when the NSTextField gets resized during editing the custom field editor no longer gets resized with it (and I need this - making an accordion
style application)
Create a "masquerading" field editor out of a NSScrollView, and using NSInvocation forward the methods to the actual surrogate field editor. This is the method I really hope would work; I've implemented all the methods as listed here; but I get an EXC_BAD_ACCESS whenever the field editor is actually loaded (e.g. when I call [customTextField selectText:nil]). I can't seem to pry any information out of the debugger even with Zombies enabled, and looking at the logs of NSObjCMessageLoggingEnabled yields nothing either. It seems like these guys got it working but that was seven years ago.
The last resort would be to drop NSTextFields completely and use NSTextViews (or instead of relying on the field editor mechanism, write one myself), but since I have many rows of data of which only one will be edited at a time, I don't want to instantiate a NSTextView for every single one of them... but then, perhaps it won't be so bad.
I ended up using option 1, and getting it to work without much difficulty. Option 2 was a complete dead end because EXC_BAD_ACCESS popped up everywhere I went.
My custom field editor now keeps a reference to a (custom) scroll view to embed itself in (vvScrollView), and inserts it into the view hierarchy. My code inside my custom field editor (NSTextView) for embedding it inside a scroll view, which is called as soon as the field editor becomes first responder and is automatically inserted into the view hierarchy:
- (void)embedSelfInScrollView {
NSView *realSuperview = [[self superview] superview];
// [self superview] is some kind of private NSClipView class
if ([realSuperview isKindOfClass:[NSTextField class]]) { // the expected behavior: this may change? TODO make less prone to chance
[realSuperview addSubview:[self vvScrollView]]; // insert into view
[[self vvScrollView] setFrameSize:[realSuperview frame].size]; // se the initial size equivalent to control size so it can autoresize the same way
// add the scrollview into the view hierarchy
[[self vvScrollView] setDocumentView:self]; // removes self from previous superview
}
}
The initial problem I had was that I was trying to insert the scrollview into the superview immediately above the field editor's (the private class of NSClipView) which broke almost every automatic sizing option (because I want to be able to resize the NSTextField while editing). Going a step further and bypassing the private class seems to work, but almost seems arbitrary.
I am wanting something similar to how iWork has the template selection screen for Pages when you can select different templates, and each view contains different info has difference sizes etc.
I have tried subclassing NSCollectionView and determining which view to display using the newItemForRepresentedObject method (as opposed to using itemPrototype view Interface Builder), but it for some reason doesn't position the views correctly, and it does not show the correct number of views for the number of items present. Here is my code. I was hoping someone may have a better way to do this, or an example of how this is done.
personView and companyView are properties in the subclassed NSCollectionView, that are IBOutlets to views in IB.
-(NSCollectionViewItem *)newItemForRepresentedObject:(id)object{
NSCollectionViewItem *collectionViewItem = [[NSCollectionViewItem alloc] init];
[collectionViewItem setRepresentedObject:object];
if([[object valueForKey:#"company"] boolValue] == YES){
NSView *view = [companyView retain];
[collectionViewItem setView:companyView];
}else{
[collectionViewItem setView:personalView];
}
return collectionViewItem;
}
(It doesn't even seem possible to make an NSCollectionView with differently-sized item views; each size would need to be a multiple or integer divisor of some "main" size, and you'd need to do massive item-checking and -reordering to be sure it's even possible to render them in a grid. Are you sure you're asking the right question?)
Also, I don't see anything like this in iWork: all the views in its template chooser are the same. (Though their NSImageView subviews are of different sizes.) I'd recommend if at all possible using the same view and changing its subviews appropriately. It's easy to, for example, bind text fields' "hidden" property or change the width of an image view. Can't you make a single view that works for both classes, changing itself appropriately depending on the represented object?