注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

云水禅心

淡若秋菊何妨瘦, 清到梅花不畏寒.

 
 
 

日志

 
 

Building Native iOS Apps with Wax(lua): Creating a Sample Application 2  

2011-08-11 11:30:16|  分类: iphone |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
http://mobile.tutsplus.com/tutorials/iphone/iphone-wax-part-2/

Pretty simple. Now all we need to do is populate the table with the data we fetch from Twitter’s servers. If you are familiar with UITableViewControllers in Objective-C, you will recognize this next method:
1
2
3
4
5
6
7
8
9
10
function tableView_cellForRowAtIndexPath(self, tableView, indexPath)
    local identifier = "TwitterTableViewControllerCell"
    local cell = tableView:dequeueReusableCellWithIdentifier(identifier) or
                             UITableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleDefault, identifier)
 
    local object = self.trends[indexPath:row() + 1] -- Must +1 because Lua arrays are 1 based
    cell:textLabel():setText(object)
 
    return cell
end

This method is a bit more complex. First, we define an identifier that is unique for all cells of the same style, but possibly with different content. In this case we call it “TwitterTableViewControllerCell”. Next, we get our instance of a UITableViewCell using a bit of Lua short-hand. Notice the “or” sandwiched between the two method calls. “cell” is set to the value of the first method call if the result of the first method call is not false or nil. Otherwise, “cell” will be set to the result of the second method call. The reason we do this is to save memory. This allows the device to only allocate memory for the 10 or so cells on the screen at one time, instead of the possibly thousands that could exist in the data source. Of course, we won’t have thousands of rows to display, but it is still a good habit to be in. Next, we set the content of cell to be the trend that is plucked from the appropriate part of the self.trends “array”. We know that this index will never be outside the range of self.trends because we told the device the size of the array in the method “tableView_numberOfRowsInSection”. Finally, we return the newly generated cell. If you press “Run” now, it should look something like this:

Blank table with table heading

Step 5 Load Data From Twitter

Now for the fun part that truly showcases Wax’s power: loading JSON data from the Internet, or, more specifically, from Twitter’s servers. Let’s get started by creating a new method called “loadDataFromTwitter”. This method should pull the JSON from Twitter’s servers and then reload the table with the new data.

1
2
3
4
5
6
7
8
9
10
11
12
13
function loadDataFromTwitter(self)
    UIApplication:sharedApplication():setNetworkActivityIndicatorVisible(true) -- show spinner
    wax.http.request{"http://api.twitter.com/1/trends.json", callback = function(json, response)
        UIApplication:sharedApplication():setNetworkActivityIndicatorVisible(false) -- hide spinner
        if response:statusCode() == 200 then
            self.trends = {} -- Reset the list of trends when the trends are refreshed
            for index,value in ipairs(json["trends"]) do -- iterate over a table with numerical keys
                table.insert(self.trends, value["name"]) -- append the value to the "array"
            end
        end
        self:tableView():reloadData()
    end}
end

Yes. It is really that simple. You define the URL to be requested and a callback to be executed when the request is done. Wax automatically identifies that the server is returning JSON and automatically converts the JSON text into a Lua table. This makes showing the network activity indicator (the spinny thing in the top right of the device, near the WiFi signal meter) incredibly easy. The JSON that is returned looks something like this. The key “trends” holds an array of objects that contain the name of the trend and the url to access all tweets with that trend.

After the trend names are stored in the self.trends variable, the tableView is reloaded which re-calls all of data methods that we defined earlier. This results in the trends being displayed in the table, very similar to the final product.

If you try running the app right now, it won’t look any different. This is because this method is never called. By calling this method from within “viewDidLoad:”, we can make sure we always show the latest trends. Add this line right before the end of the “viewDidLoad:” method:

1
self:loadDataFromTwitter()

If you hit “Run”, the app should look somewhat like this (you may have to wait a few seconds for the trends to load, watch the activity indicator!):

Almost done!

Step 6 Adding a Reload Button

This app is pretty awesome. However, a reload button that allows you to display the freshest trends would be even better. Fortunately, this is really easy.

Let’s put a reload button in the upper right hand corner of the screen. Apple actually provides a button that has a refresh icon on it for convenience, so let’s use that. Let’s start by creating a button in the “viewDidLoad:” method. Add this line before the call to “loadDataFromTwitter”:

1
local button = UIBarButtonItem:initWithBarButtonSystemItem_target_action(UIBarButtonSystemItemRefresh, self, "loadDataFromTwitter")

This creates a UIBarButtonItem that when pressed calles the “loadDataFromTwitter” method on the current object instance. If you want to experiment with other styles, you can find a list here.

Now that we have created a button, we need to add it to our interface. Using a UITableViewController makes this very easy, we simply need to call the “setRightBarButtonItem:” method on the navigation bar object instance like so (this goes after the line I gave you above):

1
self:navigationItem():setRightBarButtonItem(button)

Now, Twitter trends don’t change by the second, so you might not always see a change–but it works, I swear! If you did everything correctly, your completed app should look like this:

Refreshable!

Step 7 Extra Credit

A fun extension of this project could be to make a more visible loading indicator. This might entail putting aUIActivityIndicatorView in one of the button slots.

Conclusion

I hope you found this tutorial to be a great introduction to Wax. If you want to see more Wax tutorials on a certain subject, be sure to leave a comment and tell me what you are thinking. Who knows, maybe I will take your idea and craft an in depth tutorial from it!

Series Navigation?Building Native iOS Apps with Wax: Introduction

  评论这张
 
阅读(652)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018