Skip to content

Instantly share code, notes, and snippets.

@jonalter
Created December 20, 2011 21:39
Show Gist options
  • Save jonalter/1503402 to your computer and use it in GitHub Desktop.
Save jonalter/1503402 to your computer and use it in GitHub Desktop.
iOS: drag and drop using convertPointToView
var win = Ti.UI.createWindow({
masterWindow: true,
backgroundColor: 'white'
});
var view1 = Ti.UI.createView({
top : 20,
left : 20,
height : 100,
width : 100,
backgroundColor : 'blue'
});
win.add(view1);
var view2 = Ti.UI.createView({
top : 200,
left : 50,
height : 50,
width : 100,
backgroundColor : 'red'
});
win.add(view2);
longPress(view1, longPressCallback);
longPress(view2, longPressCallback);
var MVProps = {
movable : true,
opacity : 0
};
var movableView = Ti.UI.createView(MVProps);
win.add(movableView);
function longPress(element, callback) {
var timer;
element.addEventListener('touchstart', function(e) {
timer = setTimeout(function() {
if(callback) {
callback(e);
}
Ti.API.info('long press');
}, 500);
});
element.addEventListener('touchend', function() {
clearTimeout(timer);
});
};
function longPressCallback(e) {
Ti.API.info("e: " + JSON.stringify(e));
var cords = e.source.convertPointToView({x:e.x,y:e.y},win);
Ti.API.info('globalCords: '+cords);
MVProps.height = e.source.height+10;
MVProps.width = e.source.width+10;
var halfHeight = MVProps.halfHeight = Math.round(MVProps.height / 2);
var halfWidth = MVProps.halfWidth = Math.round(MVProps.width / 2);
MVProps.top = cords.y - halfHeight;
MVProps.left = cords.x - halfWidth;
movableView.animate({
top:MVProps.top,
left:MVProps.left,
height:MVProps.height,
width:MVProps.width,
duration:0
},function(){
movableView.top = MVProps.top;
movableView.left = MVProps.left;
movableView.backgroundColor = e.source.backgroundColor;
movableView.opacity = 1;
});
};
win.addEventListener("touchmove", function(e) {
// we check if movable is set to true so we don't grab the window
if(movableView) {
var halfHeight = MVProps.halfHeight;
var halfWidth = MVProps.halfWidth;
var cords = e.source.convertPointToView({x:e.x,y:e.y},win);
movableView.left = cords.x - halfWidth;
movableView.top = cords.y - halfHeight;
}
});
win.addEventListener('touchend', function(e){
if(e.source.masterWindow){
movableView.animate({top:MVProps.top,left:MVProps.left,duration:500},function(){
movableView.top = MVProps.top;
movableView.left = MVProps.left;
movableView.opacity = 0;
});
}
});
win.open();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment