Actual width of view
Hi,
I want to place several views side by side in a horizontal scrollView, each view contains a dynamic label so its width should be "auto". Since Titanium layout is "absolute", I have to calculate the "left" property of each view in order to place it at the good position. I would like to know if there is a way to get the actual mesured width (or height) of a view in Titanium.
Thanks
4 Answers
-
Accepted Answer
Hello Anh,
You'll want to do
view.toImage().width
. Here's an example of placing a second view next to a first one after calculating the first view's actual width:var win = Ti.UI.currentWindow; // first view var v = Ti.UI.createView({ top:10, left:10, backgroundColor: 'red', height:20, width: 'auto' }); // stick a label in it. var label = Ti.UI.createLabel({ color: 'white', top:0, left:0, height: 20, width: 'auto', text: 'This is some text. How long is it?' }); v.add(label); win.add(v); Ti.API.info('v.width=' + v.width); Ti.API.info('v.toImage().width=' + v.toImage().width); // Second view. Put it to the right of the // first view by calculating the first view's // actual runtime width. var v2 = Ti.UI.createView({ top:10, left: v.left + v.toImage().width + 2, backgroundColor: 'blue', height:20, width: 'auto' }); var label2 = Ti.UI.createLabel({ color: 'yellow', top:0, left:0, height: 20, width: 'auto', text: 'View2' }); v2.add(label2); win.add(v2);
I hope that was helpful.
Regards,
Bill
-
The accepted answer is the old way to do it!
Now 'auto' has been deprecated in the latest SDKs, so don't use it, as in my tests it stopped this working.
There is now the 'size' property available with width, height, x & y, it returns a TiRect object:
http://jira.appcelerator.org/browse/TIMOB-473
So now this will give you the value:
Ti.API.info('width:' + view.size.width);
.toImage() is going to be expensive if you have a lot of views to calculate the widths / height of!
-
Hi Bill,
Thank you, that works perfectly! -
I believe it would depend on what you are using it on and the screen size.
If it is mac or pc then it could vary.
If it was a mobile iphone app then it would be: 320x480
By the way there is textAlign: left