A ToDo App written by Swift

Source: Internet
Author: User

All of the following code is written using Xcode Version 6.0.1 (6a317).

As the team developed the use of Stroyboard in the merger when there are many inconvenience, all or use the. xib file to write this Todo App.

Want to implement the function is: TableView can add to do options, and in chronological order, you can delete, point notification function.

The effect you want to achieve is as follows:


Steps:

1, create a new project based on Singal View application, and then delete storyboard, in the new two new files Main.xib and Main.swift as the main viewcontroller, open main.xib will file The L class property of ' s owner is changed to Main (so that the associated variable can be dragged to mian.swift).

Main.xib page UI, a tableView for displaying the Todo list, and then associating a TableView variable to the Main.swift file


2, Next set Mian for Rootviewcontroller, in Appdelegate.swift write the following code:

Func application (application:uiapplication, didfinishlaunchingwithoptions launchoptions: [Nsobject:anyobject]?)- > Bool {               var viewcontroller = Main (nibname: "Main", bundle:nil)        Navigationcontroller = Uinavigationcontroller (rootviewcontroller:viewcontroller)                Self.window = UIWindow (Frame:UIScreen.mainScreen () . Bounds)        Self.window?. Rootviewcontroller = Navigationcontroller        self.window?. Makekeyandvisible ()                return True    }

Note:varViewcontroller =Main(Nibname:"Main", Bundle:Nil), which binds the mian.xib to the Mian.swift. Run a bit and you'll see the interface.

3. Then write the method of TableView data source and proxy in Main.swift. Here we are using a custom Cell. All create a new cell.xib and Cell.swift and associate them with the same behavior as above, the Cell.xib UI is as follows.


Func TableView (Tableview:uitableview, Numberofrowsinsection section:int), Int {return} FU  NC tableView (Tableview:uitableview, Cellforrowatindexpath indexpath:nsindexpath), UITableViewCell {var cell = Tableview.dequeuereusablecellwithidentifier (cellidentifier) as? Cell Var str:string if (cell = = nil) {Let Nibs:nsarray = Nsbundle.mainbundle (). loadnibnamed ("Ce ll ", owner:self, options:nil) cell = Nibs.lastobject as? Cell} cell?. Todotitle.text = "Todotitle" cell?. Time.Text = "\ (nsdate ())" Cell?.    Accessorytype = Uitableviewcellaccessorytype.disclosureindicator return cell!  } func TableView (Tableview:uitableview, Didselectrowatindexpath indexpath:nsindexpath) {} func TableView (Tableview:uitableview, Commiteditingstyle Editingstyle:uitableviewcelleditingstyle, ForRowAtIndexPath Indexpath:nsindexpath) {if Editingstyle = = UitaBleviewcelleditingstyle.delete {}} 

Run for a moment to see the following effect:


Note : In view of the UITableView scrolling performance, cell reuse is very important, through the above println (cell), scrolling cell, observe the printed cell address, you can see the cell is not reused. In

Override The following code is added to the func viewdidload () {} to make the Cell reusable.

var bundle:nsbundle = Nsbundle.mainbundle ()        var nib:uinib = uinib (nibname: "Cell", Bundle:bundle)        tableview.re Gisternib (NIB, Forcellreuseidentifier:cellidentifier)

4, the above are some of the static data, next we do some dynamic data.

4.1, add a ' + ' button in Navigationbar, to add to the user to do options

Self.navigationItem.rightBarButtonItem = Uibarbuttonitem (BARBUTTONSYSTEMITEM:UIBARBUTTONSYSTEMITEM.ADD, Target: Self, Action: "AddItem")
Response function:

Func AddItem () {let        Addvc:add = Add (nibname: "Add", Bundle:nil)        addvc.delegate = self;        Self.presentviewcontroller (ADDVC, Animated:true, Completion:nil)    }

4.2, add a add.xib and add.swift let the user input to do options, remember binding (same as Step 1), Add.xib UI as follows:


In order to receive the information entered by the user in the Add.xib in Main.swift, we define a protocol in Add.swift and then Main.swift follow this protocol to obtain user input information before the Add.xib interface disappears.

Protocol addprotocal {    func didcompleted (Addobject:add)}
The Add.swift code is as follows:

add.swift//todoapp////Created by Aaron on 14-9-17.//Copyright (c) 2014 the technology Studio. All rights Reserved.//import Uikitprotocol addprotocal {func didcompleted (addobject:add)}class Add:uiviewcontroller    {@IBOutlet var todo:uitextfield!    @IBOutlet var desc:kctextview!    @IBOutlet var time:uidatepicker!    @IBOutlet var completebtn:uibutton!        var delegate:addprotocal? Required Init (coder Adecoder:nscoder) {super.init (Coder:adecoder)} override init (Nibname Nibnameornil : String?, bundle Nibbundleornil:nsbundle?) {Super.init (Nibname:nibnameornil, Bundle:nibbundleornil)} override func Viewwillappear (animated: Bool) {setup ()} func Setup () {CompleteBtn.layer.cornerRadius = 5.0 Todo.placeholder = "please Enter the To do item "//Desc.placeholder =" Please enter a detailed description. "Todo.text = Self.todo.text Desc.text = Self.desc.text time.date = self.time.date Time.minimu MdaTe = Nsdate.date () if delegate? = = Nil {Todo.textcolor = Uicolor.lightgraycolor () todo.userinteractionenabled = False de Sc.textcolor = Uicolor.lightgraycolor () desc.userinteractionenabled = False Time.userinteractionenab  LED = False Completebtn.settitle ("good", ForState:UIControlState.Normal)}else {Todo.textcolor            = Uicolor.blackcolor () todo.userinteractionenabled = True Desc.textcolor = Uicolor.blackcolor () Desc.userinteractionenabled = True time.userinteractionenabled = True Completebtn.settitle (" Complete ", forState:UIControlState.Normal)} Let Swipegesture = Uiswipegesturerecognizer (Target:self, AC tion: "Hidekeyboard") swipegesture.direction = Uiswipegesturerecognizerdirection.down SwipeGesture.numberOfTo uchesrequired = 1 Self.view.addGestureRecognizer (swipegesture)} FuNC hidekeyboard () {println ("Swipegesture ...") Todo.resignfirstresponder () Desc.resignfirstresponder ()} func shakeanimation (sender:anyobject) {Let animation = Cakeyframeanimation () animation.keyp        Ath = "position.x" animation.values = [0, ten, -10, 0] animation.keytimes = [0, 1/6.0, 3/6.0, 5/6.0, 1] Animation.duration = 0.4 Animation.additive = True Sender.layer.addAnimation (animation, Forkey: "Shake            ")} @IBAction func Completetouch (sender:anyobject) {if (countelements (Todo.text) > 0) { Delegate?. Didcompleted (self) self.dismissviewcontrolleranimated (true, Completion:nil)}else{Shakeanim ation (Todo)}} @IBAction func Editingdidend (Sender:uitextfield) {if (countelements (sender.text) = = 0) {shakeanimation (TODO)}}}
When the TODO item is empty, there will be a small hint animation:


Correlation variables in Add.swift desc is uitextview type, Uitextview unlike Uitextfield has placeHolder, so here we introduce an OC written Kctextview, by Kctextview generation It is easy to write an API for uitextview,swift in reference to OC, create a new. h, write all the header files you need to use, and then write the object-c bridging header in the Build Settings to the path of the. h file. Then you can normally use OC-written interfaces.



Main.swift implements Addprotocal and implements the functions specified by the protocol:

Func didcompleted (addobject:add) {          tododata.append (addobject)        tableview.reloaddata ()}
Tododata is a mutable array of type Add.

The Main.swift code is as follows:

main.swift//todoapp////Created by Aaron on 14-9-16.//Copyright (c) 2014 the technology Studio. All rights Reserved.//import Uikitclass Main:uiviewcontroller, Uitableviewdatasource, UITableViewDelegate,    addprotocal {@IBOutlet var tableview:uitableview!        Let Cellidentifier = "Cell" var tododata = [Add] () override Func Viewdidload () {super.viewdidload () Setup () Registercell ()} func Setup () {self.title = "to do List" Self.navigationite M.rightbarbuttonitem = Uibarbuttonitem (BARBUTTONSYSTEMITEM:UIBARBUTTONSYSTEMITEM.ADD, target:self, action: "AddItem ")} func Registercell () {var bundle:nsbundle = Nsbundle.mainbundle () var nib:uinib = uinib (nib Name: "Cell", Bundle:bundle) tableview.registernib (NIB, Forcellreuseidentifier:cellidentifier)} Fu        NC addItem () {Let Addvc:add = Add (nibname: "Add", bundle:nil) addvc.delegate = self; Self.presentViewcontroller (ADDVC, Animated:true, Completion:nil)} func TableView (Tableview:uitableview, Numberofrowsinse Ction section:int)-Int {return Tododata.count} func tableView (Tableview:uitableview, Cellfo Rrowatindexpath Indexpath:nsindexpath), UITableViewCell {var cell = Tableview.dequeuereusablecellwithidentif IER (Cellidentifier) as? Cell Var str:string if (cell = = nil) {Let Nibs:nsarray = Nsbundle.mainbundle (). loadnibnamed ("Ce ll ", owner:self, options:nil) cell = Nibs.lastobject as? Cell} Let AddObject = Tododata[indexpath.row] as Add cell?. Todotitle.text = AddObject.todo.text cell?. Time.Text = Dateformatter (addObject.time.date) cell?.    Accessorytype = Uitableviewcellaccessorytype.disclosureindicator return cell! } func TableView (Tableview:uitableview, Didselectrowatindexpath indexpath:nsindexpath) {Let ADDVC = t Ododata[iNdexpath.row] as Add addvc.delegate = Nil Self.presentviewcontroller (ADDVC, Animated:true, Completion:nil) } func TableView (Tableview:uitableview, Commiteditingstyle Editingstyle:uitableviewcelleditingstyle, ForR Owatindexpath indexpath:nsindexpath) {if Editingstyle = = Uitableviewcelleditingstyle.delete {toDoData          . Removeatindex (Indexpath.row) Tableview.reloaddata ()}} func didcompleted (Addobject:add) { Tododata.append (AddObject) tododata.sort ({self.dateformatter ($0.time.date) < Self.dateformatter ($1.tim        e.date)})//Sort by Time Tableview.reloaddata ()} func dateformatter (date:nsdate), String { Let formatter = NSDateFormatter () Formatter.dateformat = "Yyyy-mm-dd HH:mm:ss" Formatter.locale = Nsloca    Le (localeidentifier:nsgregoriancalendar) Let datestr = formatter.stringfromdate (date) return DATESTR} Override Func DidreceiVememorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated. }}

In the end you can probably see this effect:


5, the last step, to add notification function for the project to do, this function in the previous article (iOS8 notifacation in Swift) has spoken, here does not repeat the write. Complete project code I send it on GitHub and need to get here.







A ToDo App written by Swift

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.