swift入門之TableView

IOS8更新了,oc還將繼續但新增了swift語言,能夠代替oc編寫ios應用,本文將使用swift作為編寫語言,為大家提供step by step的教程。

工具

ios每次更新都須要更新xcode,這次也不例外,但使用xcode6,須要先升級到OS X 到Yosemite。具體的升級過程這里就不說了。
須要網盤下載的同學能夠查看一下鏈接

http://bbs.pcbeta.com/viewthread-1516116-1-1.html

建立project

xocde開啟后選擇File->New->Project 建立新的project


新手教程自然選擇Single View Application



Language 自然選擇 Swift



建立好的project例如以下圖所看到的:




Work With StoryBoard

StoryBoard是IOS5和xcode 4.2開始的新特性,使用storyboard會節省手機app設計的時間,將視圖設計最大化,當然對于屌絲程序猿來說,什么board都無所謂。

箭頭表示初始view。右下角的object library還是我們最熟悉的拖拽操作。


添加一個TableView到當前的ViewController。當然你也能夠直接使用TableViewController。ViewController基本上與Android的Activity相似,都是View的控制器,用來編寫View的邏輯。


好了,能夠Run一下看看效果。

Hello world swift

最終能夠開始swift之旅了,我們來看一下AppDelegate.swift文件。

//
//  AppDelegate.swift
//  swiftTableView
//
//  Created by Chi Zhang on 14/6/4.
//  Copyright (c) 2014年 Chi. All rights reserved.
//import UIKit@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {// Override point for customization after application launch.return true}func applicationWillResignActive(application: UIApplication) {// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}func applicationDidEnterBackground(application: UIApplication) {// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}func applicationWillEnterForeground(application: UIApplication) {// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}func applicationDidBecomeActive(application: UIApplication) {// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}func applicationWillTerminate(application: UIApplication) {// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}}

是不是似曾相識,但組織上更像java和c#的邏輯,但別忘記骨子里還是object c。

打上一句hello world在application方法中。

println("helloworld")


能夠Run一下看看效果,Application方法基本上與Android中的Application類似,都是App在開始載入時最先被運行的。

Swift的語法相對object c更加簡潔,聲明函數使用func開頭,變量var開頭,常量let開頭,感覺上與javascript更加相似。

ViewController綁定TableView

最終到了本章最核心的內容了,怎樣綁定數據到TableView。
首先我們看ViewController的代碼:
//
//  ViewController.swift
//  swiftTableView
//
//  Created by Chi Zhang on 14/6/4.
//  Copyright (c) 2014年 Chi. All rights reserved.
//import UIKitclass ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}

默認的ViewController僅僅提供了兩個override的方法viewDidLoad和didReceiveMemoryWarning
我們須要讓ViewController繼承 UIViewController UITableViewDelegate UITableViewDataSource 三個類

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { ... }

添加完后,xcode會提示錯誤,當然不會像eclipse一樣自己主動幫你加入必須的方法和構造函數,須要自行加入。

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {...}

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {...}

在ViewController中聲明變量tableView用來管理我們之前在Storyboard中加入的tableView。
@IBOutlet
var tableView: UITableView
@IBOutlet 聲明改變量暴露在Interface binder中。

在viewDidLoad時,在tableView變量中添加tableViewCell

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

聲明一個String數組作為我們要綁定的數據
    var items: String[] = ["China", "USA", "Russia"]

在剛才聲明的兩個構造函數中填充邏輯。

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {return self.items.count;}func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCellcell.textLabel.text = self.items[indexPath.row]return cell}

好了,ViewController的部分基本上就寫完了。然后我們切換回StoryBoard,將Referencing Outlet與ViewController進行連接,選擇我們聲明的變量tableView。



同一時候連接Outlets中的datasource和deletegate到ViewController。



以下是完整的ViewController代碼:

//
//  ViewController.swift
//  swiftTableView
//
//  Created by Chi Zhang on 14/6/4.
//  Copyright (c) 2014年 Chi. All rights reserved.
//import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {@IBOutletvar tableView: UITableViewvar items: String[] = ["China", "USA", "Russia"]override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {return self.items.count;}func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCellcell.textLabel.text = self.items[indexPath.row]return cell}
}

好了,執行一下看看結果:


大功告成。當然我們還能夠在ViewController中添加onCellClick的方法:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {println("You selected cell #\(indexPath.row)!")}


完整代碼

轉載于:https://www.cnblogs.com/gcczhongduan/p/4230639.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376319.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376319.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376319.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Training-ActionBar

閱讀:http://developer.android.com/training/basics/actionbar/index.html 對于API11以下的兼容: Update your activity so that it extends ActionBarActivity. For example: public class Main Activit yextends ActionBarActivity{...} In your mani…

Jmeter BeanShell學習(一) - BeanShell取樣器(一)

通過利用BeanShell取樣器設置請求發送的參數。 第一步:添加BeanShell取樣器 第二步:在BeanShell中輸入執行的代碼 log.info("腳本開始執行"); //意思是將字符串輸出到日志消息中 vars.put("username","123163.com");//…

【轉】關于Python腳本開頭兩行的:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定文件編碼類型...

原文網址:http://www.crifan.com/python_head_meaning_for_usr_bin_python_coding_utf-8/ #!/usr/bin/python 是用來說明腳本語言是python的 是要用/usr/bin下面的程序(工具)python,這個解釋器,來解釋python腳本&#…

分布式系統介紹-PNUTS

PNUTS是Yahoo!的分布式數據庫系統,支持地域上分布的大規模并發操作。它根據主鍵的范圍區間或者其哈希值的范圍區間將表拆分為表單元(Tablet),多個表單元存儲在一個服務器上。一個表單元控制器根據服務器的負載情況,進行…

Jmeter BeanShell學習(一) - BeanShell取樣器(二)

利用BeanShell取樣器獲取接口返回的JSON格式的結果,并將該結果寫入到文件。 第一步:添加BeanShell取樣器 前面幾個取樣器的內容查看: https://blog.csdn.net/goodnameused/article/details/96985514 第二步:查看返回的結果格式 …

在數據庫中outlet、code、outline為聯合組件。hibarnate插入可如此插入

hibarnate對象的映射文件如下 <id name"outlet" type"string"> <column name"OUTLET" length"10" /> <generator class"assigned" /> </id> <!-- <property name"code" type"…

日怎么沒人告訴我這博客可以改博文界面的顯示寬度的

于是我妥妥的回歸了。 weebly雖然定制功能強大&#xff0c;還能穿越時空發博文&#xff0c;但是太麻煩了&#xff0c;而且用著也不像一個博客。 既然解決了這個問題&#xff0c;那Lofter除了行間距也沒什么缺點了&#xff0c;接著用吧&#xff0c;反正weebly也傳不了大圖&#…

160 - 50 DueList.5

環境&#xff1a; Windows xp sp3 工具&#xff1a; Ollydbg exeinfope 0x00 查殼 可以看出程序有加殼&#xff0c;那么我們下一步就是脫殼了。 0x01 脫殼 看上去沒什么特別的地方&#xff0c;就直接 單步跟蹤法 來脫殼吧 近call F7&#xff0c;遠call F8 來到這里 哈&…

firefox瀏覽器中silverlight無法輸入問題

firefox瀏覽器中silverlight無法輸入問題今天用firefox瀏覽silverlight網頁&#xff0c;想在文本框中輸入內容&#xff0c;卻沒想到silverlight插件意外崩潰了。google一下&#xff0c;發現這是firefox的設置問題&#xff0c;解決方法如下&#xff1a; 1、在Firefox瀏覽器地址欄…

關鍵路徑的概念和算法

AOE網&#xff1a;在一個表示工程的帶權有向圖中&#xff0c;用頂點表示事件&#xff0c;用有向邊表示活動&#xff0c;邊上的權值表示活動的持續時間&#xff0c;稱這樣的有向圖叫做邊表示活動的網&#xff0c;簡稱AOE網。AOE網中沒有入邊的頂點稱為始點&#xff08;或源點&am…

160 - 51 DueList.6

環境&#xff1a; Windows xp sp3 工具&#xff1a; Ollydbg exeinfope 0x00 查殼 發現程序沒有加殼&#xff0c;那么我們可以直接分析了。 0x01 分析 運行程序看一看 看到錯誤信息的字符串后我們可以直接搜索了。 可以看到程序會比較輸入的長度是否為8位&#xff0c;如…

寬帶上行速率和下行速率的區別

本文由廣州寬帶網http://www.ymeibai.com/整理發布&#xff0c;廣州電信寬帶報裝&#xff0c;上廣州寬帶網。 我們一般所說的4M寬帶&#xff0c;6M寬帶&#xff0c;都是指寬帶的下行速率&#xff0c;可以理解為就是下載的速度&#xff0c;平時我們用迅雷、或者網頁下載軟件時&a…

LazyInitializationException--由于session關閉引發的異常

1,頁面中進行person.department.departmentName的讀取 2,Action 中只讀取了person&#xff0c;事務作用在Service的方法中 3,后臺會有org.hibernate.LazyInitializationException出現 因為&#xff1a;Action中Service方法結束之前&#xff0c;session已經關閉了轉載于:https:/…

160 - 52 egis.1

環境&#xff1a;windows xp 工具&#xff1a; 1、OllyDBG 2、exeinfo 3、IDA 0x00 查殼 加了UPX殼&#xff0c;那么就要脫殼了。可以使用單步法來脫殼。 UPX殼還是比較簡單的&#xff0c;開頭pushad&#xff0c;找個popad&#xff0c;然后就是jmp了。 然后就可以用OD來…

玩轉MySQL之Linux下的簡單操作(服務啟動與關閉、啟動與關閉、查看版本)

小弟今天記錄一下在Linux系統下面的MySQL的簡單使用&#xff0c;如下&#xff1a; 服務啟動與關閉 啟動與關閉 查看版本 環境 Linux版本&#xff1a;centeros 6.6&#xff08;下面演示&#xff09;&#xff0c;Ubuntu 12.04&#xff08;參見文章末尾紅色標注字體&#xff09; M…

實驗八第二題

轉載于:https://www.cnblogs.com/huangsilinlana/p/3411550.html

c++ boost多線程學習(一)

本次學習相關資料如下&#xff1a; Boost C 庫 第 6 章 多線程&#xff08;大部分代碼的來源&#xff09; Boost程序庫完全開發指南 - 深入C“準”標準庫 第三版 羅劍鋒著 頭文件&#xff1a; #include <stdio.h> #include <string.h> #include <boost\versio…

C#中什么是泛型

所謂泛型是指將類型參數化以達到代碼復用提高軟件開發工作效率的一種數據類型。一種類型占位符&#xff0c;或稱之為類型參數。我們知道一個方法中&#xff0c;一個變量的值可以作為參數&#xff0c;但其實這個變量的類型本身也可以作為參數。泛型允許我們在調用的時候再指定這…

敏捷自動化測試(1)—— 我們的測試為什么不夠敏捷?

測試是為了保證軟件的質量&#xff0c;敏捷測試關鍵是保證可以持續、及時的對軟件質量情況進行全面的反饋。由于在敏捷開發過程中每個迭代都會增加功能、修復缺陷或重構代碼&#xff0c;所以在完成當前迭代新增特性測試工作的同時&#xff0c;還要通過回歸測試來保證歷史功能不…

學習c++

目錄 一 、 boost庫&#xff1a; 1. 多線程 c boost多線程學習&#xff08;一&#xff09; 二 、數據庫&#xff1a; 三、socket編程&#xff1a; c socket學習&#xff08;1.1&#xff09; c socket學習&#xff08;1.2&#xff09; c socket學習&#xff08;1.3&#x…