The TableView of Swift entry

Source: Internet
Author: User
Tags uikit





IOS8 is updated, OC will continue but new Swift language, can be used in lieu of OC to write iOS app, this article will use Swift as the writing language, to provide you with step by step tutorial. Each update to the tool iOS needs to update Xcode, this time, but with xcode6, you need to upgrade to OS X to Yosemite first. The specific upgrade process will not be said here. The students who need to download the network can check the link
Http://bbs.pcbeta.com/viewthread-1516116-1-1.html
Build PROJECTXOCDE Open and select File->new->project to create a new Project

Beginner Tutorial Natural Selection single View application


Language Natural Selection Swift


Build good project For example with what you see:



Working with Storyboardstoryboard is a new feature of IOS5 and Xcode 4.2, which saves time in mobile app design, maximizes view design, and, of course, doesn't matter what board is for the cock-and-wire program ape.
The arrows indicate the initial view. The object library in the lower right corner is our most familiar drag-and-drop operation.

Add a tableview to the current viewcontroller. Of course you can also use Tableviewcontroller directly. Viewcontroller is basically similar to the activity of Android, which is a view controller that is used to write view logic.

OK, can run a look at the effect.

Hello World Swift is finally able to start the swift journey, so let's take a look at the Appdelegate.swift file:


//
// 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 :.
    }


}

Does it seem familiar, but the organization is more like the logic of java and c #, but don't forget that there is still object c in the bones.
Type hello world in the application method.
println ("helloworld")


You can run to see the effect. The Application method is basically similar to the Application in Android. It is the first one that the App is run when it starts to load.
Swift's syntax is more concise than object c. Declaring functions start with func, variables start with var, and constant let starts. It feels more similar to JavaScript.
Binding ViewController to TableView Finally comes to the core of this chapter, how to bind data to TableView. First we look at the code of 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.
    }


}

The default ViewController only provides two override methods viewDidLoad and didReceiveMemoryWarning. We need to let ViewController inherit UIViewController UITableViewDelegate UITableViewDataSource three classes
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {...}

After adding, xcode will prompt an error. Of course, it will not actively help you to add the necessary methods and constructors like eclipse.
    func tableView (tableView: UITableView !, numberOfRowsInSection section: Int)-> Int {
       ...
    }

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

Declare the tableView variable in ViewController to manage the tableView we added in the Storyboard.
@IBOutlet
var tableView: UITableView
@IBOutlet declares that the amount of change is exposed in the Interface binder.
In viewDidLoad, add tableViewCell to the tableView variable
self.tableView.registerClass (UITableViewCell.self, forCellReuseIdentifier: "cell")

Declare a String array as the data we want to bind
    var items: String [] = ["China", "USA", "Russia"]

Fill the logic in the two constructors just declared.
    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
    }

Well, the ViewController part is basically finished. Then we switch back to StoryBoard, connect the Referencing Outlet to ViewController, and select the variable tableView we declared.


At the same time, connect the datasource and delete in Outlets to ViewController.


Here is the complete ViewController code:
//
// 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
    }
}

OK, execute it and see the result:

You're done. Of course, we can also add the onCellClick method to the ViewController:
func tableView (tableView: UITableView !, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println ("You selected cell # \ (indexPath.row)!")
    }


Complete code
TableView for swift entry


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.