3

I want to have the drag'n'drop functionality on some labels that are positioned with a absolute layout in a nativescript app. Is it even possible to move them in a new absolute position using drag'n'drop? If yes, can you explain a way to achieve this?

Thank you in advance.

4

1 回答 1

4

经过一番研究,我发现您可以通过以下步骤实现此目的:

  • 定义绝对布局
  • 在里面放一个标签
  • 在标签观察者上平移手势
  • 使用 deltaX 和 deltaY 您可以使用标签上绝对布局的静态方法 setLeft() 和 setTop() 更改标签的左侧和顶部值。

示例 xml:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
  <AbsoluteLayout>
    <Label left="10" top="10"  text="drag me" id="dragLabel" />
  </AbsoluteLayout>
</Page>

示例js代码:

var viewModule = require("ui/core/view");
var gestures = require("ui/gestures");
var absoluteLayout = require("ui/layouts/absolute-layout");
function pageLoaded(args) {

  var page = args.object;
  var dragLabel = viewModule.getViewById(page, "dragLabel");
  var observer = dragLabel.observe(gestures.GestureTypes.pan, function (panGestureEventData) {

        var deltaX = panGestureEventData.deltaX;
        var deltaY = panGestureEventData.deltaY;

        absoluteLayout.AbsoluteLayout.setTop(this, deltaY);
        absoluteLayout.AbsoluteLayout.setLeft(this, deltaX);
  }, dragLabel);
};

此外,当前版本 (1.2.x) 中的 nativescript 不支持手势中的状态。在平移手势中,状态确实是需要知道的。这是您可以执行的操作(在 ios 中),因此您可以获得状态。编辑文件 /tns_modules/ui/gestures/gestures.ios.js 并使用以下内容更改函数 _getPanData:

function _getPanData(args, view) {
   var recognizer = args.ios;
   var state = "unknown";
   switch(recognizer.state) {
   case UIGestureRecognizerStateBegan:
    state = "began";
    break;
   case UIGestureRecognizerStateChanged:
    state = "changed";
    break;
   case UIGestureRecognizerStateEnded:
    state = "ended";
    break;
   case UIGestureRecognizerStateCancelled:
    state = "cancelled";
    break;
   case UIGestureRecognizerStateFailed:
    state = "failed";
    break;
   }
   return {
       type: args.type,
       view: args.view,
       ios: args.ios,
       android: undefined,
       deltaX: recognizer.translationInView(view).x,
       deltaY: recognizer.translationInView(view).y,
       state: state
   };
}

然后,您可以使用 state 字段访问状态:

var observer = dragLabel.observe(gestures.GestureTypes.pan, function (panGestureEventData) {
  // ... panGestureEventData.state has on of the above values...
});
于 2015-09-04T08:10:37.190 回答