how to set up multiple expandable sections in a scrollview - cocoa

I need a layout similar to IB’s Inspectors, where there are multiple expandable sections, expanded by disclosure triangles, all of which are contained within a scrollview.
If only one expandable section were needed, I’d be there already: I put the expandable section in an NSBox, give the box and everything above it a top strut but no bottom strut, and give everything below it a bottom strut but no top strut. Then I set up the disclosure triangle’s action to show/hide the box and to adjust the frame size of the scrollview’s document view.
But there doesn’t seem to be a way to set the struts for multiple boxes. Either closing the disclosure triangles leaves gaps, or the boxes slide on top of each other.
I did take a look at NSOutlineView, but that’s a table; it can’t have subviews like comboboxes and buttons. (Or maybe it can, if I make custom cells, something I haven’t done yet — but I suspect those are not suited for full-featured layout.)
Can somebody point me in the right direction?

In case anybody else runs into this design challenge, I’ll post the IBAction I came up with.
This scheme uses regular, unflipped views. That is, the origin is at the lower left-hand corner. When the docSize is changed, space is added or removed from the top.
While for a single disclosure triangle, some controls need top struts and some need bottom struts, for this scheme, all controls must have both top and bottom struts. Otherwise they adjust themselves automatically, throwing everything off.
As noted at the end, there’s a considerable challenge involved when fully scrolled to the bottom. But that’s another chapter…
/**
Action called upon clicking a disclosure triangle.
Hides or discloses the box associated with the disclosure triangle.
*/
- (IBAction) discloseBox:(id)sender {
// Determine which box is governed by this disclosure triangle.
NSBox *boxTarget;
switch ([sender tag]) {
case kDT_Source:
boxTarget = self.boxSourceInfo;
break;
case kDT_Tweak:
boxTarget = self.boxTweak;
break;
case kDT_Series:
boxTarget = self.boxSeries;
break;
case kDT_Abbrevs:
boxTarget = self.boxAbbreviations;
break;
case kDT_Flag:
boxTarget = self.boxFlaggingAndComments;
break;
default:
break;
}
// Get size info on the content with and without the box.
NSView *docView = [self.svEditorMain documentView];
NSSize docSize = [docView frame].size;
CGFloat fHeightChange = [boxTarget frame].size.height;
// Before actually changing the content size, record what point is currently at the top of the window.
CGFloat dropFromTop_preChange = [self getCurrentDropFromTop];
// If the state is now on, make the box visible.
// If the state is now off, hide the box and make the height change negative.
switch ([sender state]) {
case NSOnState:
[boxTarget setHidden:NO];
break;
case NSOffState:
[boxTarget setHidden:YES];
fHeightChange *= -1;
break;
default:
break;
}
// Use the height change to prepare the adjusted docSize, but don't apply it yet.
NSSize adjustedDocSize = NSMakeSize(docSize.width, (docSize.height + fHeightChange));
// Make sure the adjustees array is populated.
[self populateVerticalAdjusteesArray];
// If the height change is positive, expand the content size before adjusting the origins, so that the origins will have space to move up into. (Space will be added at top.)
if (fHeightChange > 0)
[docView setFrameSize:adjustedDocSize];
// Get the current, pre-change Y origin of the target box.
CGFloat boxOriginY_preChange = [boxTarget frame].origin.y;
// Loop through the adjustees, adjusting their height.
NSControl *control;
CGFloat originX;
CGFloat originY;
for (NSUInteger ui = 0; ui < [self.carrVerticalAdjustees count]; ++ui) {
control = [self.carrVerticalAdjustees objectAtIndex:ui];
originY = [control frame].origin.y;
// Adjust all controls that are above the origin Y of the target box (but do nothing to the target box itself).
// Since coordinate system places origin at lower left corner, higher numbers are higher controls.
if (originY > boxOriginY_preChange) {
originX = [control frame].origin.x; // get originX just so you can assemble a new NSPoint
originY += fHeightChange;
[control setFrameOrigin:NSMakePoint(originX, originY)];
}
// Since the array was assembled in order from top down, once a member is encountered whose origin is below the target's, we're done.
else
break;
}
// If the height change is negative, contract the content size only now, after the origins have all been safely adjusted downwards. (Space will be removed at top.)
if (fHeightChange < 0)
[docView setFrameSize:adjustedDocSize];
// Left to its own devices, the scroller will maintain the old distance from the bottom, so whatever is under the cursor will jump up or down. To prevent this, scroll the content to maintain the old distance from the TOP, as recorded above.
// (This won't work if user is already scrolled to the bottom and then collapses a box. The only way to maintain the scroll position then would be to add blank space at the bottom, which would require moving the origin of all the content up. And then you would want to reverse those changes as soon as the blank space scrolled back out of view, which would require adding some trackers and monitoring NSViewBoundsDidChangeNotification.)
[self scrollMainTo:dropFromTop_preChange];
}

Check out InspectorKit. If you're using Xcode 4, however, keep in mind it no longer supports IBPlugins, so you'd have to use InspectorKit in code (and do without the drag-and-drop convenience of the Interface Builder plug-in).

Related

Override the Autolayout center values of UIButton in a Subview # viewDidLayoutSubviews

I use Autolayout for a fairly complex Menu and really need it. All Buttons, UIViews etc. of my Menu are in a separate UIView called "menuSubview".
If the user presses a button the whole "menuSubview" shifts to another position to reveal other parts of the menu. Sometimes the buttons in the menuSubview move as well. I always save the "Menu State" (with Userdefaults in the get-set variable "lastMenu") and have a function to set the alphas and centers according to the saved "Menu State".
I tried calling the "openLastMenu" function in viewDidAppear, viewDidLayoutSubview - all the "viewDid" functions of the ViewController. The "menuSubview" center and alphas of the buttons always behave as expected... but the centers of the buttons simply won't - no matter what "viewDid" I call the function in.
(the code is a lot more complex - I boiled it down to debug and state my point)
override func viewDidAppear(animated: Bool) {
if lastMenu != nil {openLastMenu()}
}
func openLastMenu(){
menuSubview.center.x = view.center.x //works
menuSubview.center.y = view.center.y + 200 //works
button1.center.x = view.center.x - 50 //why you no behave???
button2.center.x = view.center.x + 50 //why you no behave???
button3.alpha = 0 //works
button4.alpha = 0 //works
}
For debugging I even made a button Subclass to fetch the "center" values with a "didSet" if they change. Seems like after taking the correct values they change once more to their Autolayout-Position.
...oh and ignoring the constraints with "translatesAutoresizingMaskIntoConstraints" on the buttons always fucks up the whole menu. I'm starting to get crazy here :)
If you position views using autolayout, any changes to the frame, like what you do here with the center property, will be ignored.
What you need to do is identify the constraints that are you need to change to move the views in the desired position. Example:
You want to move button1 50 points to the left of view.center. Assuming view is the superview of menuSubview, you would
1) deactivate the the constraint responsible for button1's horizontal placement. How you do this mainly depends on whether you created the constraints in code or Interface Builder. The latter will require you to create outlets for some of the constraints.
2) create a new constraint between button1's centerX anchor and view's centerX anchor with a constant of -50, like so (iOS 9 code)
button1.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: -50.0).active = true

Xcode - viewDidLayoutSubviews

i have a view inside a viewController, i wanted to start the smaller view outside the viewController in the left, and animate it to the centre when i press a button. so i made it like this:
override func viewDidLayoutSubviews() {
smallView.center = CGPointMake(smallView.center.x - 400, smallView.center.y)
}
And it works perfectly!, the problem is i have a text view inside that smaller view, and every time i start editing it it jumps outside of the main viewController right where it was, and i have to press the button again to bring it inside.
How to fix this?
PS: i tried positioning it to the centre when i start editing the text view like this:
func textViewDidBeginEditing(textView: UITextView) {
smallView.center = CGPointMake(smallView.center.x + 400, smallView.center.y)
}
But it doesn't work. and the method is connected to the textView properly(delegate)
PS2: i also have imagePickerController inside my viewController.
OK, as you're using Auto Layout.
The first rule of Auto Layout (you will see this in any Auto Layout book) is that you absolutely cannot touch the frame or center of a view directly.
// don't do these
myView.frame = CGRectMake(0, 0, 100, 100);
// ever
myView.center = CGPointMake(50, 50);
You can get the frame and center but you can never set the frame or center.
In order to move stuff around using Auto Layout you need to update the constraints.
For instance if I set up a view called myView and want it to grow and shrink in height I would do something like...
Set the top constraint to the superview at 0.
Set the left constraint to the superview at 0.
Set the right constraint to the superview at 0.
Set the height constraint to 50 (for example) and save it in a property called heightConstraint.
Now to animate the change in height I do this...
self.heightConstraint.constant = 100;
[UIView animateWithDuration:1.0
animations:^ {
[self.view layoutIfNeeded];
}];
This will then animate the height from 50 (where it was when I set it) to 100.
This is the same for ANY animation of views using Auto Layout. If (for instance) I had saved the left constraint I could change that and it would increase and decrease the gap from the left edge of the superview to myView.
There are several really good tutorials about AutoLayout on the Ray Wenderlich site. I'd suggest you take a look at them.
Whatever you do, I'd strongly suggest not just disabling Auto Layout. If you don't know how to use Auto Layout then you will very quickly fall behind with iOS 8 and the new device sizes.

CListCtrl: How to maintain horizontal scroll position?

How can I maintain the horizontal scroll bar position of a CListCtrl? I periodically dump and repopulate the contents of the list control so without explicitly remembering the old position and restoring it the scroll just goes back to the top left.
I asked a related question, CListCtrl: How to maintain scroll position?, earlier but at the time I was only interested in vertical scroll position and the answer supplied solved that. However, now I want to remember and restore the horizontal scroll position (as well the vertical scroll).
First of all, it is simpler you may think. You have to save position before repopulating list and after repopulating force list control to update new content.
Also, you may take under consideration the fact that new content may have different number of items, hence you will have to set position relative to the max scroll position.
The sample code follows:
SCROLLINFO sbiBefore = { sizeof(SCROLLINFO) };
SCROLLINFO sbiAfter = { sizeof(SCROLLINFO) };
// get scroll info before
sbiBefore.fMask = SIF_ALL;
m_List.GetScrollInfo(SB_HORZ, &sbiBefore);
RenewContents();
// force control to redraw
int iCount = m_List.GetItemCount();
m_List.RedrawItems(0, iCount);
// get the scroll info after
sbiAfter.fMask = SIF_ALL;
m_List.GetScrollInfo(SB_HORZ, &sbiAfter);
double dRatio = (double)sbiAfter.nMax / sbiBefore.nMax;
// compute relative new position
sbiAfter.fMask = SIF_POS;
sbiAfter.nPos = dRatio * sbiBefore.nPos;
// set new position
BOOL bSet = m_List.SetScrollInfo(SB_HORZ, &sbiAfter);
I am sure that you can handle vertical scroll in the same manner.
In the post you mentioned, EnsureVisible is used to force update unnecessarily, since you have more proper way of doing it.
Also, using EnsureVisible would not work if last item is visible already.

Time Machine style Navigation

I've been doing some programming for iPhone lately and now I'm venturing into the iPad domain. The concept I want to realise relies on a navigation that is similar to time machine in osx. In short I have a number of views that can be panned and zoomed, as any normal view. However, the views are stacked upon each other using a third dimension (in this case depth). the user will the navigate to any view by, in this case, picking a letter, whereupon the app will fly through the views until it reaches the view of the selected letter.
My question is: can somebody give the complete final code for how to do this? Just kidding. :) What I need is a push in the right direction, since I'm unsure how to even start doing this, and whether it is at all possible using the frameworks available. Any tips are appreciated
Thanks!
Core Animation—or more specifically, the UIView animation model that's built on Core Animation—is your friend. You can make a Time Machine-like interface with your views by positioning them in a vertical line within their parent view (using their center properties), having the ones farther up that line be scaled slightly smaller than the ones below (“in front of”) them (using their transform properties, with the CGAffineTransformMakeScale function), and setting their layers’ z-index (get the layer using the view’s layer property, then set its zPosition) so that the ones farther up the line appear behind the others. Here's some sample code.
// animate an array of views into a stack at an offset position (0 has the first view in the stack at the front; higher values move "into" the stack)
// took the shortcut here of not setting the views' layers' z-indices; this will work if the backmost views are added first, but otherwise you'll need to set the zPosition values before doing this
int offset = 0;
[UIView animateWithDuration:0.3 animations:^{
CGFloat maxScale = 0.8; // frontmost visible view will be at 80% scale
CGFloat minScale = 0.2; // farthest-back view will be at 40% scale
CGFloat centerX = 160; // horizontal center
CGFloat frontCenterY = 280; // vertical center of frontmost visible view
CGFloat backCenterY = 80; // vertical center of farthest-back view
for(int i = 0; i < [viewStack count]; i++)
{
float distance = (float)(i - offset) / [viewStack count];
UIView *v = [viewStack objectAtIndex:i];
v.transform = CGAffineTransformMakeScale(maxScale + (minScale - maxScale) * distance, maxScale + (minScale - maxScale) * distance);
v.alpha = (i - offset > 0) ? (1 - distance) : 0; // views that have disappeared behind the screen get no opacity; views still visible fade as their distance increases
v.center = CGPointMake(centerX, frontCenterY + (backCenterY - frontCenterY) * distance);
}
}];
And here's what it looks like, with a couple of randomly-colored views:
do you mean something like this on the right?
If yes, it should be possible. You would have to arrange the Views like on the image and animate them going forwards and backwards. As far as I know aren't there any frameworks for this.
It's called Cover Flow and is also used in iTunes to view the artwork/albums. Apple appear to have bought the technology from a third party and also to have patented it. However if you google for ios cover flow you will get plenty of hits and code to point you in the right direction.
I have not looked but would think that it was maybe in the iOS library but i do not know for sure.

How to keep the last tree item of NSOutlineView in the most bottom of a Sidebar?

I'd like to have the same behavior of special items as it's done in the Things application. I mean Logbook and Trash items in the bottom part of the Sidebar:
Logbook and Trash items are in the most bottom http://tinyurl.com/lhctza
Please advise any way to implement the same functionality in the sidebar tree.
I feel that special ‘spacer’ tree item should be used together with outlineView:heightOfRowByItem: method.
However, I can't find how to calculate the total height of all visible items (incl. space between groups).
You might try simply having two outline views: One of fixed height, pinned to the bottom of their superview, and the other of variable height, with its bottom immediately above the top of the first. The fixed-height outline view would contain those Logbook and Trash items, and the variable-height outline view would contain all the others.
The tricky part would be making this play nice with a scroll view, but I think you could do it. I imagine you'd put them both in a fully-resizable NSView and make that the scroll view's document view.
I've decided to hardcode the solution by adding 8 pixels of height for every root item in group style.
So, the code looks like this:
- (CGFloat)outlineView:(NSOutlineView *)ov heightOfRowByItem:(id)item;
{
if (![item isSpacer]) return [ov rowHeight];
static const CGFloat ADDITIONAL_SPACE = 8.0f;
NSUInteger numberOfRootGroups = 2;
CGFloat heightOfRows = [ov rowHeight] * ([ov rowForItem:item] + 1)
+ ADDITIONAL_SPACE * numberOfRootGroups;
CGFloat heightOfSidebar = [[ov superview] frame].size.height;
return MAX(0.0f, heightOfSidebar - heightOfRows);
}
Thanks to everybody for support!

Resources