Tuesday, 31 July 2012

Titanium: Handling orientation changes on iPhone and iPad



This thing bugs me for a while when I was working on a recent project.
In my project, I need to handle the orientation changes so that I can change the layout and images accordingly. At first, I found a solution in the official Q&A forum, and it works perfectly well on the simulator:

function getOrientation(o) {
switch (o) {
case Titanium.UI.PORTRAIT: {return 'portrait';};break;
case Titanium.UI.UPSIDE_PORTRAIT: {return 'portrait';};break;
case Titanium.UI.LANDSCAPE_LEFT: {return 'landscape';};break;
case Titanium.UI.LANDSCAPE_RIGHT: {return 'landscape';};break;
default: return 'none';
}
}
Ti.Gesture.addEventListener('orientationchange', function(e){
var orientation = e.getOrientation;
if(orientation == "portrait"){
//do something
}else{
//do something else
}

It looks fine. But when I test it on the iPad, something terrible happened. When I tilt the iPad vertically, the UI keeps changing in an unwanted way. That is annoying. So why this happened?
After some searching, I found out that there are actually 6 orientations (x,y,z axis) including face_up and face_down! We need to get rid of those 2 in the orientation change event, so I added another condition before the if statement:

if(orientation == 0 || orientation == 5){
//do nothing
}else if(orientation == "portrait"){
//do something
}else{
//do something else
}

Well of course, that solved the problem!

Customizing Title bar in iOS 5

In iOS 5,customizing title bar with backgroundImage is pretty simple:
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"image.png"] forBarMetrics:UIBarMetricsDefault];
But for the text font and color, it requires a little bit more work:      
    [[UINavigationBar appearance] setTitleTextAttributes:
    [NSDictionary dictionaryWithObjectsAndKeys:
    [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0],
    UITextAttributeTextColor,
    [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
    UITextAttributeTextShadowColor,
    [NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
    UITextAttributeTextShadowOffset,
    [UIFont fontWithName:@"STHeitiSC-Medium" size:0.0],
    UITextAttributeFont, nil]];