Subviews counted in root CALayer's sublayers? - objective-c

I noticed today, when adding 1 CALayer and 2 subviews to my view, when I run the following code in my UIView instance:
[self.layer.sublayers count]
This returns 3. Does this mean that a subview is also considered a sublayer? If I only wanted the CALayers that I've drawn in my sublayers call, how would i do that?

Yes, each UIView has an underlying CALayer which is added to its superview's layer when the view is added to the superview.
I don't know the ideal way to find only your own layers. Since sublayers is an NSArray (as opposed to an NSSet), it means it's an ordered list, which means you can be sure that the order in which you add views to the superview is the same order they will appear in said array.
Thus, if you add your UIViews first, and then add your own drawn CALayers afterwards, you can probably get your own by accessing the objects starting at index 2 (skipping 0 and 1) in sublayers.
Of course, if you then add or remove views to the superview you'd have to modify this value, so presuming this actually works, you'll want to somehow dynamically generate it.
You can ascertain the index for a layer as you add it, using indexOfObject: on the sublayers property. A safer route might be to simply store this index somewhere in a list and to access the sublayers with indices from that list only.

If I only wanted the CALayers that I've drawn in my sublayers call,
how would i do that?
You can do this by making the view that is currently a subview of self into a sibling view by having them both be subviews on a containing view. Then your current self.layer.sublayers would just contain the CALayers you added manually.
One way to think about it is that it is the layer hierarchy, not the view hierarchy which defines the render hierarchy. The view hierarchy is just a wrapper to handle interactivity that UIView adds to its underlying CALayer graphics. Thus, when you add a subview to a view, it simultaneously, though in some sense independently, adds its layer as a sublayer to the view's layer. You could probably override this functionality in a subclass or category on UIView...

From the CALayer documentation:
delegate
Specifies the receiver’s delegate object.
#property(assign) id delegate
Discussion
In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer.
Availability
Available in OS X v10.5 and later.
Related Sample Code

Related

Layer hosting NSView within NSOutlineView

I am trying to create a custom NSView that hosts a CALayer hierarchy to perform efficient display. This NSView is then embedded within a NSTableCellView that is displayed by a View-Based NSOutlineView.
The problem is that whenever I expand or collapse an item, all rows are being moved, but the layer's content remains displayed at the position it was before changing the outline.
Scrolling the NSOutlineView seems to refresh the layers and they resync with their rows at that point.
I have debugged this behavior using Instruments and it seems that the scrolling provokes a layout operation which updates the layers with a setPosition: call that should have occured when expanding or collapsing items.
Here is some sample code for a simple layer hosting NSView subclass.
#interface TestView : NSView
#end
#implementation TestView
- (instancetype)initWithFrame:(NSRect)frameRect
{
self = [super initWithFrame:frameRect];
CAShapeLayer* layer = [CAShapeLayer layer];
layer.bounds = self.bounds;
layer.position = CGPointMake(NSMidX(self.bounds), NSMidY(self.bounds));
layer.path = [NSBezierPath bezierPathWithOvalInRect:self.bounds].CGPath;
layer.fillColor = [NSColor redColor].CGColor;
layer.delegate = self;
self.layer = layer;
self.wantsLayer = YES;
return self;
}
#end
I have tried a lot of potential solutions to this problem but I couldn't find any interesting method that gets called on the NSView instance that could be overriden to call [self.layer setNeedsDisplay] or [self.layer setNeedsLayout]. I also tried various setters on the CALayer itself such as :
layer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
layer.needsDisplayOnBoundsChange = YES;
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;
Can anyone help me figure out how to make this layer display properly inside a NSOutlineView?
I ended up answering my question. The problem wasn't in the way my TestView was implemented. I simply missed one of the steps for enabling CoreAnimation support within the application. The relevant reference is within the Core Animation Programming Guide.
Basically, in iOS Core Animation and layer-backing is always enabled by default. On OS X, it has to be enabled this way :
Link against the QuartzCore framework
Enable layer support for one or more of your NSView objects by doing one of the following
In your nib files, use the View Effects inspector to enable layer support for your views. The inspector displays checkboxes for the selected view and its subviews. It is recommended that you enable layer support in the content view of your window whenever possible
For views you create programmatically, call the view’s setWantsLayer: method and pass a value of YES to indicate that the view should use layers.
Once I enable layer support on any of the NSOutlineView's parents, the various glitches are solved.
It is difficult to read the NSOutlineView reference documents and find the information about cell reuse that is likely giving you fits here.
You may have looked at outlineViewItemDidCollapse: but it's kind of a useless for our issue, because it doesn't have a pointer to an NSView, and that's because it's older than view-based outline views.
Perhaps the one helpful mention, buried within the NSOutlineViewDelegate protocol, down in the section on view-based NSOutlineView methods, there is a single mention within outlineView:didRemoveRowView:forRow: that:
The removed rowView may be reused by the table, so any additionally inserted views should be removed at this point.
In other words, when you call the outline view's makeViewWithIdentifier:owner:, for a cellView or rowView with a particular ID you often get a recycled view. Especially often because of collapse. Incidentally, that method is from the NSTableView superclass, and in that reference, there's also this comment:
This method may also return a reused view with the same identifier that is no longer available on screen. If a view with the specified identifier can’t be instantiated from the nib file or found in the reuse queue, this method returns nil.
So you have the option of altering the view hierarchy or niling properties in didRemoveRowView:forRow. However, buried within a third cocoa reference, that for NSView, there is within the commentary on prepareForReuse, this comment:
This method offers a way to reset a view to some initial state so that it can be reused. For example, the NSTableView class uses it to prepare views for reuse and thereby avoid the expense of creating new views as they scroll into view. If you implement a view-reuse system in your own code, you can call this method from your own code prior to reusing them.
So, TL;DR, you need to implement prepareForReuse.
The pertinent references are (mostly) the superclasses of both NSOutlineView and NSTableCellView.
And, FWIW, there was a similar question here, where the questioner seems to indicate things are even worse than I think, in that NSOutlineView is more creative behind the scenes than NSTableView.
In my own work with outline views and embedded NSTextViews, I've seen wildly terrible rendering hiccups relating to expand/collapse/scroll that I seem to have managed in just the NSOutlineViewDelegate methods. On iOS they did everyone the favor of renaming makeViewWithIdentifier to the more explicit dequeueReusableCellViewWithIdentifier.
You shouldn't have to enable layer backing for any of the ancestor views (like the outline view).
In my experience, the layer immediately assigned to a view (as opposed to sublayers) doesn't need its bounds, position, or autoresizing mask to be set. It is automatically made to track the bounds of the view. In fact, I would avoid setting those properties, just in case that breaks the automatic synchronization with the view's bounds rect.
So, the question is: how are you arranging for the view to move or resize with its superview? Are you using auto layout? If so, did you turn off its translatesAutoresizingMaskIntoConstraints? If yes to both, what constraints are you setting on the view? If no to either, how did you position the view within its superview? What frame did you set? Also, is the superview configured to autoresize its subviews (probably yes, since that's the default)? What is your view's autoresizingMask?
You could also override -setFrameOrigin: and -setFrameSize: in your custom view class and call through to super. Also, add logging to show when that's happening and what the new frame rect is. Is your view being moved as you expect when you expand or collapse rows?

Optimizing UIScrollView with subviews

I have problem with UIScrollView, I try create sth like table with own rows ( separate nib ). Everything works good with 1-10 rows, but problem occurs with more than 20 elements. The application starts working slow, and stunt. Is there any solution to optimalize scroll view for 100-200 own subviews?
Use UITableView. That's precisely what it's designed for.
UITableView and UICollectionView are both optimizing by removing subviews that are no longer needed and putting them in a reuse queue. By reusing those views the system does not have to create and destroy their backing layers but can reuse them. This way you only have ever as many subviews on screen as can fit.
Typically you want to add/remove visible subviews in either the layoutSubviews of a scroll view subclass or the corresponding didScroll delegate method. Personally I prefer the layoutSubviews since it is a bit earlier in the chain of events.
Basically you would get a reusable subview from your reuse queue as soon as at least 1 px of the subview should appear within the bounds of the scroll view and remove the subview as soon as no pixel of it is visible any more.
If you use UITableview or UICollectionView instead of a plain scroll view they provide a mechanism to register views in NIB for certain reuse identifiers and then the dequeueing will automatically load a new instance of a subview from NIB is none is queue or dequeue one if there is.

setNeedsDisplay does not trigger drawRect in subviews as expected

I'm struggling with setNeedsDisplay. I thought it was supposed to trigger calls of drawRect: for the view for which it is called and the hierarchy below that if it's within the view's bounds, but I'm not finding that to be the case. Here is my setup:
From the application delegate, I create a view whose size is a square that covers essentially the whole screen real estate. This view is called TrollCalendarView. There is not much that happens with TrollCalendarView except for a rotation triggered by the compass.
There are 7 subviews of TrollCalendarView called PlatformView intended to contain 2D draw objects arranged around the center of TrollCalendarView in a 7-sided arrangement. So when the iPad is rotated, these 7 views rotate such that they are always oriented with the cardinal directions.
Each of the PlatformView subviews contains 3 subviews called Tower. Each tower contains 2D draw objects implemented in drawRect:.
So, in summary, I have TrollCalendarView with empty drawRect:, and subviews PlatformView and Platformview -> Tower that each have drawRect implementations. Additionally, Tower lies within the bounds of Platform, and Platform lies within the bounds of TrollCalendarView.
In TrollCalendarView I've added a swipe recognizer. When I swipe happens, a property is updated, and I call [self setNeedsDisplay] but nothing seems to happen. I added NSLog entries to drawRect: method in each of these views, and only the TrollCalendarView drawRect: method is called. Ironically, that is the one view whose drawRect method will be empty.
There is no xib file.
What do I need to do to ensure the drawRect method in the other subviews is called? Is there documentation somewhere that describes all the nuances that could affect this?
I'm struggling with setNeedsDisplay. I thought it was supposed to trigger calls of drawRect for the view for which it is called and the hierarchy below that if it's within the view's bounds
No, that is not the case. Where did you get that idea?
-setNeedsDisplay: applies only to the view to which it is sent. If you need to invalidate other views, you need to add some code to send -setNeedsDisplay: to them, too. That's all there is to it.
I think this is an optimization in the framework; if your subviews don't need to draw again, then this is a major performance improvement. Realize that almost anything animatable does not require drawrect (moving, scaling, etc).
If you know that all of your subviews should be redrawn (and not simply moved), then override setNeedsDisplay in your main view and do like this:
-(void) setNeedsDisplay {
[self.subviews makeObjectsPerformSelector:#selector(setNeedsDisplay)];
[super setNeedsDisplay];
}
I have tested this, and it causes all subviews to be redrawn as well. Please note that you will earn efficiency karma points if you somehow filter your subviews and make sure you only send that to subviews which actually need redrawn... and even more if you can figure out how not to need to redraw them. :-)

CGContext is being covered by a UIView

I'm not that great with Core Graphics, but I am drawing text on the screen to my CGContext. I am doing this immediately after I add a standard, opaque UIView to my user interface.
Does anyone know why the text I draw after I add my UIView is still at the "bottom" of the user interface?
Thanks in advance.
iOS, like OS X, uses a compositing window manager. Adding and removing UIViews sets their position in the view hierarchy; when and how they're drawn is managed separately. There is no guaranteed relation between when a view is added and when it'll be drawn, and no reason to guarantee one. The content of a view is cached and composited as required from that copy.
If you want to do custom drawing, create a custom UIView subclass, add it to the hierarchy according to where you want it to appear and do your drawing in drawRect: or one of the other override points if you want to render off thread.

"refresh" view on device rotation

I have my view set up in viewDidLoad. All the different frames and such of the subviews have been defined relative to self.view. Therefore it doesn't matter what size self.view is the subviews will always shrink or expand to fit (as it were).
So when I rotate my device I want the view to rotate (easy enough with shouldAutoRotateToInterfaceOrientation:...) but the subviews stay the same shape.
Calling [self viewDidLoad]; makes all the elements fit, but puts a new layer on top of the previous layout (which is obvious... but i'm just saying to explain what I mean).
Is there any way to refresh the frames of the subviews or something? I don't know what other people do to be honest. Am I going to have to put ALL of my views into the .h file as properties and do everything manually on didRotate...?
You have three options:
If autoresizing masks are good enough to position your views, assign the correct autoresizing mask to each subview when you create them.
If autoresizing masks are not sufficient, override willAnimateRotationToInterfaceOrientation:duration: and reposition your subviews in that method. I would create a custom method that takes the orientation as a parameter and is responsible for laying out all subviews. You can then call this method from willAnimateRotationToInterfaceOrientation:duration: and from viewDidLoad.
You could also create a custom UIView subclass and make your view controller's view an instance of this class. Then override layoutSubviews to position all subviews depending on the view's size. This approach implies that your custom view manages its subviews instead of the view controller.