[IOS] using Swift to develop a TODO application, iostodo
Address: http://blog.callmewhy.com/2014/09/15/todo-list-in-swift/
Background
I believe many iOS programmers are still holding a wait-and-see attitude towards Swift. This is just a few days after the arrival of the little guy, and he is still in the perfect stage. Second, the learning cost is high, it may take a few days to read the official documents. However, in recent years, it has been difficult to promote and use the documents in engineering projects, but it is not enough for my work.
Yes, I thought so at the beginning. Until one day, I met it: Swift Tutorial-To Do List App. This is a good video tutorial on YouTube. It teaches you how to complete a TODO application. The function is simple, that is, adding tasks and browsing tasks. I sorted out the video content. Although there is no deep content, it is quite suitable as an entry-level applet.
Target Audience: iOS developers who have certain Objective-C Development basics but have no idea about Swift, but have Xcode6 installed.
Guest officer, we can see it here. Why don't we open Xcode6 and play two games? Play together! Come on. Come on!
Requirement
We want to make a very simple little item. Like the Demo on the official website, it is a TODO list (TODO: to-do list) with the following features:
- There is a list showing TODO
- There is a page to add TODO
- Click Add to display the new TODO list in the list.
It's so easy. Let's get started!
Create a project
Create a new project and select the Tabbed Application template. The project name is MyTodoList. Remember to select Swift as the development language. Xcode creates a Swift project:
ADD management class
The first class we need is a TodoList manager, which is used to store the data in the TODO list and perform some basic operations for adding, deleting, modifying, and querying. We name itTodoManager
.
Right-click the folder on the left, select New File, and select Cocoa Class. The Class name isTodoManager
, Inherited from NSObject, Xcode will automatically add a TodoManager. swift file for us.
The variables and functions we define in Swift are global attributes, so that we can define a TodoManager object outside the class.todoManager
, Simple implementation of the singleton mode:
import UIKitvar todoManager : TodoManager = TodoManager ()class TodoManager: NSObject {}
Next, define a struct to represent a TODO item. It has two attributes: one is the task name and the other is the task description:
struct todo { var name = "Un-Named" var desc = "Un-Described"}
Add a todos array to TodoManager to store all tasks:
class TodoManager: NSObject { var todos = [todo]()}
Finally, define a method.addTask
To add a task:
class TodoManager: NSObject { var todos = [todo]() func addTask(name: String, desc: String) { todos.append(todo(name: name, desc: desc)) }}
OK.TodoManager
Even if it is complete.
DEVELOPMENT INTERFACE
Return to StoryBoard and delete the automatically generated content (several labels) on the page:
Then add a UITableView to FirstViewController:
Select the Tab Bar to edit the display name and image of the Tab Bar:
Next, let's take a look at Second View. Change the Title of the second Tab Bar to Add:
In this way, the basic page is handled.
Data Display First View Controller
Under the first Tab, move the mouse over UITableView, right-click and drag it to View Controller, and select DataSource and Delegate:
Return to the Code, open the FirstViewController. swift file, and addUITableViewDelegate
AndUITableViewDataSource
The two protocols. Press and hold the Command key and click the protocol name to view the Protocol Declaration, so as to know the methods to be implemented. The method name is exactly the same as that in OC. You only need to convert it to the Swift syntax. After completionFirstViewController
It looks like this:
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ 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. } // UITableView DataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoManager.todos.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Default") cell.textLabel?.text = todoManager.todos[indexPath.row].name cell.detailTextLabel?.text = todoManager.todos[indexPath.row].desc return cell }}
Second View Controller
Drag some controls to build the basic framework. A Label is used as the title. Fill in the TODO Name and description for the two textfields respectively, and then add the Add button. The basic framework looks like this:
Then we direct the Delegate of the two textfields to the View Controller, because we hope that the keyboard will automatically play back after we input and click Return. InSecondViewController.swift
AddUITextFieldDelegate
And implementtextFieldShouldReturn
Delegate method, in the method, throughresignFirstResponder
Play the keyboard back:
// UITextField Delegatefunc textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true}
We hope that the user can retrieve the keyboard when clicking the background image, and we can rewrite it.touchsBegan
Method, addendEditing
Method:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true)}
Define two attributes to get the values in the text box, switch to the Assistant view, and right-click and drag to create two variables:
Then we create an IBAction to process the Click Event of the Add button:
In the click event, we want to complete the following tasks:
- Add a TODO item in todoManager.
- Collapse the keyboard
- Clear content in TextField
- Switch the TabBar to the todo label to view the result in real time.
After OKaddBtnClick
The method is as follows:
@IBAction func addBtnClick(sender: AnyObject) { todoManager.addTask(todoText.text, desc: descText.text) self.view.endEditing(true) todoText.text = "" descText.text = "" self.tabBarController?.selectedIndex = 0}
In this way, the task of adding TODO is complete.
Delete data
The interfaces for deleting data and Objective-C are the same.commitEditingStyle
Method implementation. Open the FirstViewController. swift file and add a TableView attribute in the code to refresh the data:
Delete is actually deleted.todoManager
Oftodos
The corresponding data in the array. We can useremoveAtIndex
Implementation, rememberreloadData
Refresh TableView:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if(editingStyle == UITableViewCellEditingStyle.Delete) { todoManager.todos.removeAtIndex(indexPath.row) } todoTableView.reloadData()}
Test
This is the end of the basic development work. We can run and run the application.
First add a TODO:
Click Add to view the added TODO items in TableView:
Slide to see the delete button:
Click Delete. The deletion is successful:
Summary
I don't know how you feel here. Anyway, I feel like water is exploding! There are no profound technical points or innovative things. It is just a well-regulated small application.
Yes, indeed. However, I hope that you can familiarize yourself with Swift and the new partner ^_^ through such a simple example.
Click here to download the complete project source code. Have fun.
I hope you can give me some guidance and suggestions on ios development.
1. First, learn the basic syntax of oc, and then try to compile the implementation of some classic algorithms. During this period, you should be familiar with various xcode operations. Generally, many oc books will design the basic usage of xcode. If you have a good foundation, this process will take about a week or two.
At this time, you are far away from IOS development, because you only learned some syntax. Real ios development requires a large number of controls. Each control has a specific class, a specific delegate method, and so on.
2. I need to find a book about ios development and learn from the implementation of various UI components one by one. Such as tableview and navigation. I am familiar with it, so I can learn more complex components. In the meantime, we should also try to learn more about the establishment and use of various views. This is very important.
3. Regarding swift, I don't think it is urgent for beginners to learn about ios, because many of the syntax and oc features of ios apps developed based on swift are particularly similar, so learning oc is a good thing for you to learn swift. Second, there is no need to use swift for development in a short time. The new version of xcode6 is not very smooth and often crashes. After the official release, it is not too late to study.
With swift, it is also necessary to learn objectivec for ios development.
Swift was launched, and obj-c will not be discarded too quickly. Obj-c has a complete set of APIs. Currently, obj-c must be used for projects in the near future or within 1-2 years. Swift is only used to play games. Apple's official suggestion is that the main project is written in obj-c, and swift is used to develop plug-ins.