Search code examples
javascriptscrollviewtitanium-mobile

Deleting a view from a ScrollView


Developing in Titanium Mobile.

I need to remove a view from a scrollView when a delete button is clicked. I have a custom event firing when my button is clicked, which the scrollView listens for. My question is, how do I reference the view that needs to be deleted? These views are added to the scrollView dynamically, and there is no unique information about the view. I tried passing the view itself when firing the custom event, but this does not work. How do I tell the scrollView which view to delete?


Solution

  • When you have a delete button inside the view - that's a piece of cake :) Just get its' parent and delete it - scrollView.remove(e.source.parent);

    Here I created a demo page:

    var scrollView = Titanium.UI.createScrollView({ 
        contentWidth: 'auto', 
        contentHeight: 'auto', 
        top: 0, 
        showVerticalScrollIndicator: true, 
        showHorizontalScrollIndicator: true,
        layout: 'vertical'
    }); 
    
    var colors = ['red', 'green', 'blue', 'orange', 'purple', 'yellow'];
    
    for (var i = 0; i < 6; i++) {
    
        var view = Ti.UI.createView({ 
            backgroundColor: colors[i], 
            borderRadius: 10, 
            width: 300, 
            height: 200, 
            top: 10,
            id: i
        });
        scrollView.add(view); 
    
        var deleteButton = Ti.UI.createButton({
            borderRadius: 3,
            style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
            backgroundGradient: {
                type: 'linear', 
                colors: [ '#c7c7c7', '#686868' ], 
                startPoint: { x: 0, y: 0 }, 
                endPoint: { x: 0, y: 30 }, 
                backFillStart: false
            },
            title: 'Delete view ' + i,
            font: { fontSize: 12, fontWeight: 'bold' },
            color: '#fff',
            width: 120,
            height: 30
        });
        view.add(deleteButton);
    
        deleteButton.addEventListener('click', function(e) {
            Ti.API.info(e.source.id); // use this ID
            scrollView.remove(e.source.parent);
        });
    
    }
    
    Ti.UI.currentWindow.add(scrollView);