swift入门之TableView

IOS8更新了,oc还将继续但新增了swift语言,能够代替oc编写ios应用,本文将使用swift作为编写语言,为大家提供step by step的教程。

工具

ios每次更新都须要更新xcode,这次也不例外,但使用xcode6,须要先升级到OS X 到Yosemite。具体的升级过程这里就不说了。
须要网盘下载的同学能够查看一下链接


建立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 UIKit

class 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 UITableViewCell
        
        cell.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 UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
    
    @IBOutlet
    var tableView: UITableView
    var 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 UITableViewCell
        
        cell.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