Sarah R Sarah R - 1 year ago 94
Javascript Question

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

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); = 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' });


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.

After some trial and error, I've found that


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

Answer Source

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;

hope that helped. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download