官术网_书友最值得收藏!

Creating a "Pull to Refresh" mechanism in iOS

What if you want the user to be able to refresh the feed data in your table? You could create a regular button, or possibly check for new data after arbitrary time intervals. Alternatively, you can implement a cool "pull and refresh" mechanism, which has become the de facto standard refresh method in iOS.

In this recipe for our recipe finder app, we'll implement this very type of refresh mechanism for our recipes' feed using the built-in, native refresh control.

How to do it...

Open your recipes.js file and type the following under the creation of tblRecipes:

if (Ti.Platform.name === "iPhone OS") {
        var p2r = Ti.UI.createRefreshControl({
            tintColor: '#000'
        });

        tblRecipes.refreshControl = p2r;

        p2r.addEventListener('refreshstart', function(e) {

            refresh(function() {
                p2r.endRefreshing();
            });

        });
} else if (Ti.Platform.name === "android") {
        win.addEventListener("focus", refresh);
     }

Next, we need to modify the refresh function to support a callback that will run when the refresh is completed. Change the function definition to this:

function refresh(callback) {

Finally, add the following code before the closing of the function and after you set the table data:

if (typeof callback === 'function'){
              callback();
            }

Now launch the app and pull the recipe table down. You'll see the refresh spinner working, and the table will refresh!

How it works...

What we're doing here is using the built-in iOS refresh control and attach this to a table, and then telling the control what to do when it's pulled. We made our job easier by creating a refresh function, which can be passed to a callback function. So, when the refresh method is called, it refreshes the table and then calls the callback function, which in this case tells the refresh control to hide.

The last part of our code block checks for Android, intercepts the focus event of the window (which fires whenever the window is shown), and then calls the refresh function.

主站蜘蛛池模板: 遂昌县| 婺源县| 姚安县| 屏东县| 江口县| 迭部县| 合水县| 江津市| 承德市| 浦县| 宜川县| 东乡县| 云梦县| 营山县| 信丰县| 商洛市| 吴川市| 临城县| 西乌珠穆沁旗| 宜章县| 海盐县| 兴业县| 岳普湖县| 凉城县| 凌源市| 乾安县| 广宗县| 曲靖市| 高平市| 合江县| 门源| 巴彦县| 新蔡县| 梁山县| 徐水县| 静安区| 皋兰县| 常德市| 吉木萨尔县| 景东| 莲花县|