Skip to content

Instantly share code, notes, and snippets.

@chmiiller
Created January 18, 2016 15:39
Show Gist options
  • Save chmiiller/1f6804e729796511bd2d to your computer and use it in GitHub Desktop.
Save chmiiller/1f6804e729796511bd2d to your computer and use it in GitHub Desktop.
Titanium - Smoothly animating an input field along with the iOS Keyboard.
function init() {
Titanium.App.addEventListener('keyboardframechanged', $.typingArea.animateKeyboard);
}
function scrollToBottom() {
$.listView.scrollToItem(0, $.section.items.length - 1, {
animated : true
});
}
function changeListViewBottom(bottom) {
$.listView.bottom = bottom;
}
init();
"#listView" : {
width: Ti.UI.FILL,
height: Ti.UI.FILL,
top: 0,
separatorColor: 'transparent',
backgroundColor: 'transparent'
}
<Alloy>
<Window id="winConversation">
<ListView id="listView">
<ListSection id="section"/>
</ListView>
<Require id="typingArea" src="ios_input_field.xml" onSetListViewBottom="changeListViewBottom" onScrollToEnd="scrollToBottom"/>
</Window>
</Alloy>
var keyboard_height,
keyboard_y,
resize_threshold,
max_typing_height = Ti.Platform.displayCaps.platformHeight * 0.18;
exports.animateKeyboard = function(e) {
if(!keyboard_height || keyboard_height < e.keyboardFrame.height) {
keyboard_height = e.keyboardFrame.height;
}
if(!keyboard_y || (keyboard_y < e.keyboardFrame.y && (e.keyboardFrame.y - keyboard_y) < 50)) {
keyboard_y = e.keyboardFrame.y;
}
// In case the user has hidden the text prediction area.
if(e.animationDuration == 0) {
$.vwMessage.animate({
bottom: e.keyboardFrame.height - 50,
duration: 250,
curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
}, function() {
$.vwMessage.bottom = e.keyboardFrame.height - 50;
$.trigger('setListViewBottom', $.vwMessage.rect.height + e.keyboardFrame.height - 50);
});
}
if((e.keyboardFrame.y - keyboard_y) > 50 || e.animationDuration != 0) {
$.vwMessage.animate({
bottom: $.vwMessage.bottom == 0 ? e.keyboardFrame.height - 50 : 0,
duration: e.animationDuration * 1000,
curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
}, function() {
$.vwMessage.bottom = ($.vwMessage.bottom < 1 ? e.keyboardFrame.height - 50 : 0);
$.trigger('setListViewBottom', $.vwMessage.rect.height + ($.vwMessage.bottom < 1 ? 0 : e.keyboardFrame.height - 50));
});
}
_.delay(scrollToEnd, 500);
};
function scrollToEnd() {
$.trigger('scrollToEnd');
}
<Alloy>
<!-- This is the view that you want to animate along with the iOS soft keyboard -->
<View id="vwMessage" />
</Alloy>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment