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

2019-07-21 13:17发布

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.

2条回答
混吃等死
2楼-- · 2019-07-21 14:00

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. :)

查看更多
Bombasti
3楼-- · 2019-07-21 14:19

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.

查看更多
登录 后发表回答