在 NativeScript 中访问元素高度

Geo*_*rds 5 javascript xml nativescript

我正在尝试编写一个本机脚本应用程序,它bottle在我的 xml 中检索视图/元素的呈现高度。我尝试了以下代码,但不幸的是,出现错误(如下所示)。任何指导将不胜感激。

JS:

var viewModule = require("ui/core/view");
var page;

exports.fabTap = function (args) {
      page = args.object;
      var bottle = page.getViewById("bottle");
      console.log("Height: " + bottle.height);
  }
Run Code Online (Sandbox Code Playgroud)

XML:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:FAB="nativescript-floatingactionbutton" actionBarHidden="true" loaded="pageLoaded">
  <GridLayout columns="*, *, *, *" rows="15*, 5*, 20*, 5*, 5*, 5*, 5*, 20*, 20*" width="100%" height="100%" style.backgroundColor="white" >
    <Image src="res://logo" row="0" col="1" colSpan="2" stretch ="aspectFit" class="logo"/>
    <Image id="bottle" src="res://bottle_outline" row="2" col="0" rowSpan="6" colSpan="2" stretch="aspectFit"/>
  </GridLayout>
</Page>
Run Code Online (Sandbox Code Playgroud)

无法读取未定义的属性“高度”。

Pet*_*aev 1

这是因为在fabTap处理程序中,args.object不是页面而是 FAB 小部件本身。因此,当您调用getViewById它时,它会搜索 FAB 小部件的视图层次结构,并且那里没有瓶子:) 您应该按如下方式更改代码:

var viewModule = require("ui/core/view");
var page;
exports.pageLoaded = function (args) {
   page = args.object;
}
exports.fabTap = function (args) {
   var bottle = page.getViewById("bottle");
   console.log("Height: " + bottle.height);
}
Run Code Online (Sandbox Code Playgroud)

  • @GeorgeEdwards 似乎只有在设置属性而不返回实际属性时才会返回“height”。尝试打印“bottle.getMeasuredHeight()”,看看是否有区别。 (6认同)