首页 > 设计 > WEB开发 > 正文

3.29.控制子组件的位置和滚动

2023-08-05 15:52:29
字体:
来源:转载
供稿:网友
3.29.1 问题
你需要滚动一个父组件并且移动除了一个子组件之外的其它所有子组件。
3.29.2 解决办法
在容器定义的scrollChildren方法内,根据verticalScrollPosition属性重新定位子组件。
3.29.3 讨论
容器的scrollChildren 方法测量容器的contentPane 这个DisplayObject,它包含了添加到容器中的所有子组件,同时确定在滚动的时候测量到的子组件要显示出多少。contentPane则根据horizontalScrollPosition 和verticalScrollPosition 属性移动。容器自身则像是contentPane 的遮罩一样,并且contentPane 的位置由滚动条的相对位置以及容器的ViewMetrics 属性值确定。

下面的代码段把顶部组件的y 位置存储起来,允许用户拖拽组件的同时保持组建距离父亲容器顶部位置的不变,而正常设置其它组件:
+展开
-XML
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxmlwidth="500"
height="500">

<mx:Script>
<![CDATA[
private var top:TopComponent;
//store the y position
private var topY:Number;
private function showTop():void
{
top = new TopComponent();
addChild(top);
top.verticalScrollPolicy = "none";
top.x = 200;
top.y = 100;
topY = top.y;
top.addEventListener(MouseEvent.MOUSE_DOWN, dragTop);
}
private function dragTop(event:Event):void
{
top.startDrag(falsethis.getBounds(stage));
top.addEventListener(MouseEvent.MOUSE_UP,
stopDragTop);
}p
private function stopDragTop(event:Event):void
{
topY = top.y;
top.stopDrag();
top.removeEventListener(MouseEvent.MOUSE_UP,
stopDragTop);
}o
override protected function scrollChildren():void
{
super.scrollChildren();
if(top){
top.y = verticalScrollPosition+topY;
//
top.verticalScrollPosition =
this.verticalScrollPosition/height *
top.height;
}
}

]]>
</mx:Script>
<mx:Panel>
<mx:Label text="LABEL BABEL"/>
<mx:Label text="LABEL BABEL"/>
<mx:Label text="LABEL BABEL"/>
</mx:Panel>
<mx:Panel y="500height="200">
<mx:Label text="LABEL BABEL"/>
<mx:Label text="LABEL BABEL"/>
<mx:Label text="LABEL BABEL"/>
</mx:Panel>
<mx:Button click="showTop()"/>
</mx:Canvas>

这有点过于简单了,而且同样的分类逻辑可以被扩展以给容器全部子组件创建自定义的滚动。如果你已经知道容器全部子组件可以滚动,你可以覆盖scrollChildren 方法,如下:
+展开
-ActionScript
private var dir:String;
private function handleScroll(event:ScrollEvent):void {
dir = event.direction;
}
override protected function scrollChildren():void {
var i:int = 0;
do{
var comp:DisplayObject = getChildAt(i);
if(comp is Container){
trace( Container(comp).maxVerticalScrollPosition );
dir == "horizontal" ?
Container(comp).horizontalScrollPosition =
horizontalScrollPosition *
(Container(comp).maxHorizontalScrollPosition/maxHorizontalScrollP
osition) :
Container(comp).verticalScrollPosition =
verticalScrollPosition *
(Container(comp).maxVerticalScrollPosition/maxVerticalScrollPosit
ion);
}i
++;
while (i < numChildren)
}

本例使用maxVerticalScrollPosition 和maxHorizontalScrollPosition 计算每个容器滚动的正确位置。容器通过从其所有子组件的宽和高中减去容器的实际宽和高来决定这些属性。在前面的代码段中,每个子组件的maxVerticalScrollPosition 和maxHorizontalScrollPosition 都由父亲的值来分隔以确定子组件滚动多少。这保证即使父亲和子组件不一样大小,传给子组件的滚动量也是正确的。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表