系列教程:使用 Swift 开发 iOS 应用

Apple recently announced a pretty major change to the way iOS apps have been developed in the past, an entirely different programming language called Swift which replaces Objective-C. In my efforts to learn the new language, I’ve decided I will be posting regularly as I step through the learning process, sharing everything I find. This is the first post of many on the topic, and I hope you decide to follow along!

It is highly likely that much of the code examples here of Swift will be changed later. This is partially because my development style is to write now to test an idea, and refactor later, and it is partially because I (like everyone) am completely new to Swift and am starting out fresh. So it is likely as I learn things over time, the course of this tutorial will change. I will update code examples as needed, but not so much that the learning process is not also demonstrated. I think this is also a useful process to see.


So I’m going to start with a pretty basic app and explain how the code works. Ready? Here we go…

The Basics

Swift does away with the standard of declaring variables by starting with their type names, and instead opts to use a Javascript-like ‘var’ keyword to define any variable.

So for instance in Objective-C where you have this:

NSString *myString = @"This is my string.";

You now have this:

var myString = "This is my string."

Meanwhile constants are expressed with the ‘let’ keyword

let kSomeConstant = 40

In this case kSomeConstant is implicitly defined as an integer. If you want to be more specific you can specify which type it is like so:

let kSomeConstant: Int = 40

With both arrays and dictionaries, they are described using brackets []

var colorsArray = ["Blue", "Red", "Green", "Yellow"]
var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]

There’s a lot more to go over, but I think these basics are important to get a start going on to the tutorial. So with that, let’s move on to Hello World.

Hello World

Hello World in Swift and iOS

First, we’re going to write the simplest app imaginable to get started, Hello World.

Our app will only do one thing: print “Hello World” to the console. You’ll need a developer copy of Xcode in order to follow along, which requires a developer account. If you have one, head on over to http://developer.apple.com and get your copy before we begin.

So now you’ve got your IDE set up. Let’s write hello world out to the console. This example demonstrates the simplest app that can be built, and more importantly shows that you’re environment is set up correctly.

Set up an Xcode project using the single-view application template, and make sure you opt for Swift as the language.

You should now find an AppDelegate.swift file in the project hierarchy. Inside of this file find the line that says:
"// Override point for customization after application launch."

Replace this line with our amazing hello world code:

println("Hello World")

Now press run and you should see a blank app boot up, and the words “Hello World” print to the console. Congratulations! You just wrote your first app in Swift! This app probably won’t win any awards, let’s trying doing something a little deeper…

Adding a Table View

In this section, we’re going to actually put some stuff on the screen, yay!
Open up your Main.storyboard file in Xcode and lets drag in a “Table View” object from the Object Library. Position this fullscreen in your app window and make sure it lines up with the edges. If you run the app at this point, you should see an empty table view in the simulator.

Now we need to set up a delegate and data source for the table view. This is easy to do in interface builder. Just hold control, and then click and drag from the tableview to the “View Controller” object in your storyboard’s hierarchy, and select ‘data source’. Repeat with the ‘delegate’ options.

Okay, now let’s dig in to the protocol methods for Table Views. Because we’re using the UITableViewDataSource and UITableViewDelegate in our view controller, we need to modify the class definition to say as much.

So open ViewController.swift and modify this line:
class ViewController: UIViewController {

to this:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

Command+clicking on either of these protocols will show the required functions at the very top. In the case of a tableview, we need at least these two:
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

So let’s modify our View Controller class by adding these two functions
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

cell.text = “Row #(indexPath.row)”
cell.detailTextLabel.text = “Subtitle #(indexPath.row)”

return cell }

The first method is asking for the number of rows in our section, in this simple tutorial we just hard-code 10, but normally it would be the length of an array controller. This example is intentionally simple.

The second method is where the magic happens. Here we create a new instance of a UITableViewCell called cell, using the Subtitle cell style.
Then, we assign the text value of this cell to the string “Row #(indexPath.row)”
In Swift, this is how variables are embedded within a string. What we’re doing is retrieving the value of indexPath.row by inserting (indexPath.row) in to our string, and dynamically replacing it with the row number of the cell. This allows results such as “Row #1″, “Row #2″, etc.

The detail text label is only available in the Subtitle cell class, which we are using here. We set it similarly to “Subtitle #1″, “Subtitle #2″, and so on.

Go ahead and run your app and you’ll now see an amazing list of cells with titles and subtitles indicating their row numbers. This is one of the most common ways to display data in iOS, and will be sure to serve you well. For the full code to my View Controller file, take a look here: ViewController.swift

In part 2, we’re going to explore using the iTunes search API to create an app capable of finding and displaying albums within the iTunes store.

原文地址:http://jamesonquave.com/blog/developing-ios-apps-using-swift-tutorial/

Share Comments