How to get the actual height of a label with auto-height

ⅰ亾dé卋堺 提交于 2019-12-11 01:46:00

问题


I'm aware that this question has appeared in various forms before, but none of the solutions worked out for me... I'm using the Titanium API 2.1.3, and building for iPhone.

I use a lot of common JS, so I have this:

exports.Header = function(title){
var l = Ti.UI.createLabel({
    text: title,
    height: 'auto',
    textAlign: 'left',
    color: '#989898',
    font: {fontSize: exports.defaultFontSize+10, fontFamily: exports.defaultFont, fontWeight: 'bold'}
});
return l;
};

And I'm calling the label like so:

var qLabel = gui.Header(question);
qLabel.top = 5;
qLabel.left = 10;
qLabel.right = 10;
qLabel.color = "#3B3B3B";
qLabel.font = {fontSize: gui.defaultFontSize+4, fontWeight: 'bold'};

I've tried all sorts of things to get the height of the label so far, for instance:

qLabel.toImage().height // this returns auto
qLabel.getRect().height // this returns 0

and the same thing with getSize().height (this returns 0 as well) or getHeight() (returns auto). I've tried adding it to the parent view first, and then reading the height, but nothing... the last thing I did was this:

var qqv = Ti.UI.createView({ width: 'auto', height: 'auto' });

qqv.add(qLabel);
qLabel.show();

Ti.API.info(qLabel.rect.height);
Ti.API.info(qLabel.size.height);
Ti.API.info(qqv.rect.height);
Ti.API.info(qqv.size.height);

they all return 0.

I'm getting pretty desperate at this point, and I don't know if this problem is because of the API version I'm using or whatever...any help is appreciated.

EDIT: After some trial and error, I've found that

qLabel.toImage().height;

returns some number, however, it doesn't seem to be the correct height.


回答1:


You can use postlayout event

here is the sample code that will get your label height

label.addEventListener('postlayout', function(e) {
    var label_height = e.source.rect.height;
    alert(label_height);
});

hope that helped. :)




回答2:


I've ran into the same problem and I didn't want to use a postlayout event on every single element. Instead I used the size property which is a read only and contains the actual sizes of the element. I compared this with the event data from a postlayout event and they gave the exact same values.

So if you want to get the height of an element I suggest you using $.label1.size.height instead of adding an event listener all the time. This will also be alot better for the performance of your app because the postlayout event will be fired alot.



来源:https://stackoverflow.com/questions/13012421/how-to-get-the-actual-height-of-a-label-with-auto-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!