您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Wax 框架速成教學(二):安裝與第一個 TableView

編輯:iOS 開發綜合

建立新專案

打開 Xcode,從 User Templates 中找到 Wax 專案模板並建立一個新專案。從現在起,我們用 APP_ROOT 代表專案所在的路徑。執行 App,你會在 iPhone 模擬器中看到「Hello Lua」字樣。

開始使用 Lua

你不需要在 Xcode 裡編寫 Lua 程式碼,它們全部放在 APP_ROOT/scripts 目錄下,用任何你喜歡的編輯器去修改即可。Wax 標準庫位於 APP_ROOT/wax/lib/stdlib 目錄。

如果你用 TextMate,可以在 APP_ROOT 目錄執行 rake tm 從專案開啟,還能安裝 wax-bundle 取得快捷鍵支援。若你堅持用 Xcode,可以試試語法高亮外掛。而如果你用 vi 或 Emacs,想必早就裝好 Lua 支援了。

建立一個 TableView

首先建立檔案 APP_ROOT/scripts/MyTableViewController.lua,用以下語法建立新的 Objective-C 控制器類別:

waxClass{"MyTableViewController", UITableViewController}

接著實作 init 函式,在其中設定 tableView 的內容並呼叫父類的 init 方法(就像在 Objective-C 裡那樣),再完成各個 DataSource 方法。最終 MyTableViewController.lua 大致如下:

waxClass{"MyTableViewController", UITableViewController}

function init(self)
   self.super:initWithStyle(UITableViewStylePlain)
   self.things = {"Planes", "Trains", "Automobiles"}
   return self
end

function numberOfSectionsInTableView(self, tableView)
   return 1
end

function tableView_numberOfRowsInSection(self, tableView, section)
   return #self.things
end

function tableView_cellForRowAtIndexPath(self, tableView, indexPath)
   local identifier = "MyTableViewControllerCell"
   local cell = tableView:dequeueReusableCellWithIdentifier(identifier) or
       UITableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleDefault, identifier)
   local thing = self.things[indexPath:row() + 1] -- 必須 +1,因為 Lua 陣列從 1 開始
   cell:textLabel():setText(thing)
   return cell
end

把控制器掛到主視窗

最後建立 MyTableViewController 實例並加入主視窗,這需要修改 APP_ROOT/scripts/AppDelegate.lua。它等同於 Objective-C 裡的 UIApplicationDelegate:

require "MyTableViewController"

waxClass{"AppDelegate", protocols = {"UIApplicationDelegate"}}

function applicationDidFinishLaunching(self, application)
   local frame = UIScreen:mainScreen():bounds()
   self.window = UIWindow:initWithFrame(frame)
   self.controller = MyTableViewController:init()
   self.window:addSubview(self.controller:view())
   self.window:makeKeyAndVisible()
end

執行看看——你已經用 Lua 打造出一個真正的 UITableView 了,是不是很棒?

以 Framework 方式安裝 Wax

你可以從官方網站下載 framework,然後依下列步驟整合進專案:

1. 用 Xcode 打開專案,把 wax.framework 拖到 frameworks 群組下,記得勾選「Copy items into destination group's folder」。

2. 建立一個 init.lua(務必加入應用程式 bundle),寫入:

puts("ZOMG, LUA IS RUNNING")
puts("Here is Lua talking to ObjC %s", tostring(UIApplication:sharedApplication()))

3. 打開 AppDelegate,匯入 Wax 標頭檔:

#import "wax/wax.h"

4. 在 application:didFinishLaunchingWithOptions: 方法中加入啟動語法:

wax_start("init.lua", nil);

若要啟用 Wax 擴充功能,則改用:

#import "wax/wax_http.h"
#import "wax/wax_json.h"
#import "wax/wax_filesystem.h"
wax_start("init.lua", luaopen_wax_http, luaopen_wax_json, luaopen_wax_filesystem, nil);

完成後 build and run,你就能在 Xcode 主控台看到 Lua 輸出的內容了。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved