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.
Related
I have wrapping NSTextView instances stacked vertically, for example:
The quick brown fox
jumps over the lazy dog
Jackdaws love my big
sphinx of quartz
I need to move between them with up/down arrows. For example, when the cursor is positioned after the l in "lazy" and the user presses the down arrow, the cursor should jump right after the y in "my" – like it would do if these sentences were in the same text view.
By default, when the down arrow is pressed while the cursor is at the last wrapped line, a text view moves it to the end of that line. While I can use textView(_:doCommandBy:) in NSTextViewDelegate to detect the "arrow down" selector and override the default behavior, there are two problems:
I can determine if the cursor is at the last line by getting its position via the selectedRanges property and then checking for the newline character after this position, but it is not possible to know if it is at the last wrapped line, i.e. near the border of the current text view.
I need to know the X coordinate of the cursor to place it at approximately the same X coordinate in another text view (the fonts won't necessarily be fixed-width, so I can't rely on the character count).
I suppose both of them can be resolved via NSLayoutManager, but I can't wrap my head around all of its available methods.
It turned out to be relatively easy, here's what I've done (the examples are in C#). First, boundingRect(forGlyphRange:in:) gets the cursor's location in the current view:
var cursorLocation = new NSRange(CurrentTextView.SelectedRange.Location, 0);
var cursorCoordinates = CurrentTextView.LayoutManager.BoundingRectForGlyphRange(cursorLocation, CurrentTextView.TextContainer).Location;
Then if the second text view is below, the insertion point will be at 0 on the Y axis:
var insertionPoint = new CGPoint(cursorCoordinates.X, 0);
And if it is above, then another view's height should be used (reduced by 1, otherwise the resulting character index will be incorrect and the cursor will be placed at the end of the line):
var insertionPoint = new CGPoint(cursorCoordinates.X, AnotherTextView.Bounds.Size.Height - 1);
After getting the insertion point, another view needs to become the first responder and then characterIndexForInsertion(at:) does the job:
Window.MakeFirstResponder(AnotherTextView);
var index = AnotherTextView.CharacterIndex(insertionPoint);
AnotherTextView.SelectedRange = new NSRange(index, 0);
I have an gameobject1(added Scroll Rect component)and inside of it another gameobject2(The Scroll rect component's content).In gameobject2 has images.The number of images can be 10 or 20..(Any numbers).The Movement Type is Elastic.As you know it will stop scrolling only until gameobject2 height's length. How to stop on dynamic number's of length.In gameobject2 the number of images can be different. It depends on search results. The results can be 5,8, or 200. So I need to scroll until last of search result.So how to stop scrolling on exactly length in Scroll rect component?
You can use ContentSizeFitter component. GameObject with name "Content", is a content for scrollRect component of "ScrollView"-gameObject.
RectTransform#SetSizeWithCurrentAnchors
I use this a lot when building dynamic scrolling lists. After adding all the items I want (and each having a known size, and all positioned using that size) I update the content's RectTransform with the new size (total number of objects added * size of the object).
For example, I have this code:
int i = 0;
//for each item in a list of skills...
IEnumerator<Skill> list = SkillList.getSkillList();
Transform skillListParent = GuiManager.instance.skillPanel.transform;
while(list.MoveNext()) {
Skill sk = list.Current;
//create a prefab clone...
GameObject go = Main.Instantiate(PrefabManager.instance.SKILL_LISTITEM, skillListParent) as GameObject;
//set its position...
go.transform.localPosition = new Vector3(5, i * -110 -5, 5);
//add a button event or other data (some lines omitted)...
Transform t1 = go.transform.FindChild("BuyOne");
t1.GetComponent<Button>().onClick.AddListener(delegate {
doBuySkill(sk);
});
t1.GetChild(0).GetComponent<Text>().text = Main.AsCurrency(sk.getCost(1)) + " pts";
//track how many...
i++;
}
//update rect transform
((RectTransform)skillListParent).SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, (i * 110 + 10));
I am presently learning C# and have chosen as a project to write a simple colour picker control ; however things have changed substantially since I last looked at writing code and I have struck this problem.
I am using the Mousedown event in my control to get the mouse coordinates as a Point - this is working fine and returns exactly what I would expect - the mouse coordinates relative to my control; however when I try and do a check against the control location I am returned a value as a Point showing the position of my control relative to the form which in certain cases the mouse coordinates will be outside the bounds of because their values will be less than the relative start position of the control I.E I click at pixel 1,1 in the control - the mouse position is 1,1 but because the control is located at 9,9 relative to the form the location of the mouse is less than the bounds of the control - I have absolutely no idea how to fix this, I have been attempting to sort it out with PointToClient and PointToScreen to no avail as they seem to come up with outlandish values can someone please help me out it's driving me insane.
I've managed to sort this out myself so thought I'd post the answer and it can hopefully help someone else. I was having problems getting Point values that were relative to the same pixel origin : this sorted it.
private void ColourPicker_MouseDown(object sender, MouseEventArgs e)
{ // Probably being paranoid but I am worried about scaling issues, this.Location
// would return the same result as this mess but may not handle
// scaling <I haven't checked>
Point ControlCoord = this.PointToClient(this.PointToScreen(this.Location));
int ControlXStartPosition = ControlCoord.X;
int ControlYStartPosition = ControlCoord.Y;
int ControlXCalculatedWidth = ((RectangleColumnsCount + 1) * WidthPerBlock ) + ControlXStartPosition;
int ControlYCalculatedHeight = ((RectangleRowsCount + 1) * HeightPerBlock) + ControlYStartPosition;
// Ensure that the mouse coordinates are comparible to the control coordinates for boundry checks.
Point ControlRelitiveMouseCoord = this.ParentForm.PointToClient(this.PointToScreen(e.Location));
int ControlRelitiveMouseXcoord = ControlRelitiveMouseCoord.X;
int ControlRelitiveMouseYcoord = ControlRelitiveMouseCoord.Y;
// Zero Relitive coordinates are used for caluculating the selected block location
int ZeroRelitiveXMouseCoord = e.X;
int ZeroRelitiveYMouseCoord = e.Y;
// Ensure we are in the CALCULATED boundries of the control as the control maybe bigger than the painted area on
// the design time form and we don't want to use unpaited area in our calculations.
if((ControlRelitiveMouseXcoord > ControlXStartPosition) && (ControlRelitiveMouseXcoord < ControlXCalculatedWidth))
{
if((ControlRelitiveMouseYcoord > ControlYStartPosition) && (ControlRelitiveMouseYcoord < ControlYCalculatedHeight))
{
SetEvaluatedColourFromPosition(ZeroRelitiveXMouseCoord, ZeroRelitiveYMouseCoord);
}
}
}
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).
Wee.
So I finally figured out how the iIntegral member of TVITEMEX works. The MSDN docs didn't think to mention that setting it while inserting an item has no effect, but setting it after the item is inserted works. Yay!
However, when using the TVS_HASLINES style with items of variable height, the lines are only drawn for the top part of an item with iIntegral > 1. E.g. if I set TVS_HASLINES and TVS
Here's what it looks like (can't post images WTF?)
Should I manually draw more of the lines in response to NM_CUSTOMDRAW or something?
Yes, Windows doesn't do anything with the blank space obtained from changing the height.
From the MSDN:
The tree-view control does not draw in the
extra area, which appears below the
item content, but this space can be
used by the application for drawing
when using custom draw. Applications
that are not using custom draw should
set this value to 1, as otherwise the
behavior is undefined.
Alright, problem solved.
I failed to find an easy answer, but I did work around it the hard way. It's basically just drawing the extra line segments in custom draw:
// _cd is the NMTVCUSTOMDRAW structure
// ITEMHEIGHT is the fixed height set in TreeView_SetItemHeight
// linePen is HPEN of a suitable pen to draw the lines (PS_ALTERNATE etc.)
// indent is the indentation size returned from TreeView_GetIndent
case CDDS_ITEMPREPAINT : {
// Expand line because TreeView is buggy
RECT r = _cd->nmcd.rc;
HDC hdc = _cd->nmcd.hdc;
HTREEITEM hItem = (HTREEITEM) _cd->nmcd.dwItemSpec;
if( r.bottom - r.top > ITEMHEIGHT ) {
HGDIOBJ oldPen = SelectObject( hdc, linePen );
// Draw any lines left of current item
HTREEITEM hItemScan = hItem;
for( int i = _cd->iLevel; i >= 0; --i ) {
// Line should be drawn only if node has a next sibling to connect to
if( TreeView_GetNextSibling( getHWnd(), hItemScan ) ) {
// Lines seem to start 17 pixels from left edge of control. But no idea
// where that constant comes from or if it is really constant.
int x = 17 + indent * i;
MoveToEx( hdc, x, r.top + ITEMHEIGHT, 0 );
LineTo( hdc, x, r.bottom );
}
// Do the same for the parent
hItemScan = TreeView_GetParent( getHWnd(), hItemScan );
}
SelectObject( hdc, oldPen );
}
}
The pattern from the PS_ALTERNATE brush sometimes doesn't align perfectly with line drawn by the control, but that's hardly noticeable. What's worse is that even though I have the latest common controls and all the service packs and hotfixes installed, there are still bugs in TreeView documented way back in 2005. Specifically, the TreeView doesn't update its height correctly. The only workaround I've found for that is to force some collapsing/expanding of nodes and do a few calls to InvalidateRect.
If the variable-height nodes are at the root level, though, there doesn't appear to be anything you can do. Luckily I don't need that.