2

尝试创建具有动态高度的视图时遇到了一些问题。

“post_comment”是我将显示文本的标签。文本的长度必须是动态的,并且“containComment”视图必须调整其高度才能显示此标签。

var post_comment = Titanium.UI.createLabel({
        color:'#000',
        text:L(randomText),
        top:10,
        bottom:30,
        left:4,
        width:220,
        height:'auto',
        font: { fontSize:11 },
    });

    var comment_height = 100;

    post_comment.addEventListener('postlayout', function(e) {
        comment_height = e.source.rect.height;
        alert(comment_height); <--------- 1
    });

    var containComment = Titanium.UI.createView({
        layout :'horizontal',
        contentWidth:'100%',
        height: comment_height,
    });
    alert(comment_height);  <-------- 2

我使用 postlayout 来获取高度,但由于某种原因,我无法在函数之外获得相同的值。

我在箭头指示的 2 个位置测试了“comment_height”。在 1 中,显示的高度是正确的。但是在 2 处,高度始终是默认值 100。我认为这是由于“comment_height”不是全局的,所以我将它发送到脚本的头部,但它仍然不能解决问题。

任何帮助,将不胜感激。

4

1 回答 1

6

通过让视图自动调整大小,这是最简单的。如果您看到此代码,它会执行您想要的操作:

var win = Titanium.UI.createWindow({  
    backgroundColor:'white'
});

var post_comment = Titanium.UI.createLabel({
    color:      'white',
    top:        10,
    bottom:     30,
    left:       4,
    width:      220,
    height:     Ti.UI.SIZE,
    font:       { fontSize:11 },
    backgroundColor: 'blue',
    text:       "My Text"
});


var containComment = Titanium.UI.createView({
    height: Ti.UI.SIZE,
    backgroundColor: 'red'
});


containComment.add(post_comment);

win.add(containComment);

win.open();

但是,当这样完成时,您无法从视图中读取高度值。即containComment.height 不会给你一个值。

如果您真的需要高度的数值,我知道的唯一方法是将其转换为图像,然后读取图像的大小:

var containImage = containComment.toImage();

// height = containImage.height

希望有帮助

于 2013-09-27T13:48:45.947 回答