Swift 书面 ToDo App

Swift 书面 ToDo App

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

下面的代码是使用的全部Xcode Version 6.0.1 (6A317)书面。

因为当使用团队开发stroyboard在并购的诸多不便的时间,所有或使用.xib该文件准备ToDo App.

想要实现的功能:TableView 够添加待做选项。并依照时间先后排序,能够实现删除。到点通知功能。

想要实现的效果例如以下:

Swift 书面 ToDo App   Swift 书面 ToDo App   Swift 书面 ToDo App

步骤:

1、新建一个基于Singal View Application 的project,然后删掉storyboard,在新建两个新文件 Main.xib 和 Main.swift 作为基本的ViewController,打开 Main.xib 将 File’s Owner的l类属性改为 Main(这样才干够将关联变量拖动到 Mian.swift )。

Main.xib 页面UI。一个用于展示todo list 的 tableView,然后关联一个 tableView 变量到 Main.swift文件

Swift 书面 ToDo App

2、接下来设置 Mian 为rootViewController,在AppDelegate.swift中做写例如以下代码:

 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
    }


注意: 
var viewController =
Main(nibName:
“Main”, bundle:
nil) ,用来将 Mian.xib 与 Mian.swift 进行绑定。run 一下你就能够看到界面了。

3、然后在Main.swift 中编写一下TableView 的数据源和代理的方法。这里我们用的是 自己定义的 Cell。全部新建一个 Cell.xib 和 Cell.swift 并将它们关联起来,做法和上面的同样,Cell.xib UI 例如以下。

Swift 书面 ToDo App

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    
    func 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("Cell", 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 一下就能够看到例如以下效果:

Swift 书面 ToDo App

注意:考虑到UITableView的滚动性能。Cell 的重用很重要,通过上面的 println(cell),滚动Cell,观察打印出来的 Cell 地址。能够看到 Cell 并没有进行重用。

在 

override func viewDidLoad() { } 中加入以下的代码使 Cell 重用。

var bundle: NSBundle = NSBundle.mainBundle()        var nib: UINib = UINib(nibName: "Cell", bundle: bundle)        tableView.registerNib(nib, forCellReuseIdentifier: cellIdentifier)

4、以上讲到的都是些静态的数据,接下来我们做一些动态数据。

  4.1、在NavigationBar 添加一个 ‘+’ button,用来给用户添加待做选项

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addItem")

响应函数:

func addItem() {
        let addVC: Add = Add(nibName: "Add", bundle: nil)
        addVC.delegate = self;
        self.presentViewController(addVC, animated: true, completion: nil)
    }

 

 4.2、新增一个 Add.xib 和 Add.swift 让用户输入待做选项。记得绑定(同步骤1),Add.xib UI例如以下:

Swift 书面 ToDo App

为了在Main.swift 中接收到 Add.xib 中用户输入的信息,我们在 Add.swift 定义一个协议。然后Main.swift 遵循这个协议,在Add.xib 界面消失前获取用户输入信息。

protocol AddProtocal {
    func didCompleted(addObject: Add)
}

Add.swift 代码例如以下:

//
//  Add.swift
//  ToDoApp
//
//  Created by aaron on 14-9-17.
//  Copyright (c) 2014年 The Technology Studio. All rights reserved.
//

import UIKit

protocol 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 = "请输入待做项"// desc.placeholder = "请输入具体描写叙述。" todo.text = self.todo.text desc.text = self.desc.text time.date = self.time.date time.minimumDate = NSDate.date() if delegate? == nil { todo.textColor = UIColor.lightGrayColor() todo.userInteractionEnabled = false desc.textColor = UIColor.lightGrayColor() desc.userInteractionEnabled = false time.userInteractionEnabled = false completeBtn.setTitle("好", forState: UIControlState.Normal) }else { todo.textColor = UIColor.blackColor() todo.userInteractionEnabled = true desc.textColor = UIColor.blackColor() desc.userInteractionEnabled = true time.userInteractionEnabled = true completeBtn.setTitle("完毕", forState: UIControlState.Normal) } let swipeGesture = UISwipeGestureRecognizer(target: self, action:"hideKeyboard") swipeGesture.direction = UISwipeGestureRecognizerDirection.Down swipeGesture.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(swipeGesture) } func hideKeyboard() { println("swipeGesture....") todo.resignFirstResponder() desc.resignFirstResponder() } func shakeAnimation(sender: AnyObject) { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 10, -10, 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{ shakeAnimation(todo) } } @IBAction func editingDidEnd(sender: UITextField) { if (countElements(sender.text) == 0) { shakeAnimation(todo) } } }

ToDo项为空时会有一个小小的提示动画:

Swift 书面 ToDo App

Add.swift 中的关联变量 desc 是UITextView 类型的,UITextView 不像 UITextField 有 placeHolder ,所以这里我们引入一个 OC 写的 KCTextView ,由 KCTextView 取代 UITextView,swift 中引用 OC 写的 API easy,新建一个 .h 。把你须要用到的头文件统统写在里面,然后 Build Settings 中的 Object-C Bridging Header 写入 .h 文件的路径就可以。接着就能够正常使用 OC 写的接口了。

Swift 书面 ToDo App

Main.swift 实现 AddProtocal,并实现协议规定的函数:

func didCompleted(addObject: Add) {
  
        toDoData.append(addObject)
        tableView.reloadData()
}

toDoData的是一个 Add类型的可变数组。

Main.swift 代码例如以下:

//
//  Main.swift
//  ToDoApp
//
//  Created by aaron on 14-9-16.
//  Copyright (c) 2014年 The Technology Studio. All rights reserved.
//

import UIKit

class 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.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addItem")

    }
    
    func registerCell() {
        var bundle: NSBundle = NSBundle.mainBundle()
        var nib: UINib = UINib(nibName: "Cell", bundle: bundle)
        tableView.registerNib(nib, forCellReuseIdentifier: cellIdentifier)
    }
    
    
    func addItem() {
        let addVC: Add = Add(nibName: "Add", bundle: nil)
        addVC.delegate = self;
        self.presentViewController(addVC, animated: true, completion: nil)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toDoData.count
    }
    
    
    func 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("Cell", 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 = toDoData[indexPath.row] as Add addVC.delegate = nil self.presentViewController(addVC, animated: true, completion: nil) } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath 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.time.date)})//按时间排序 tableView.reloadData() } func dateFormatter(date: NSDate) -> String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.locale = NSLocale(localeIdentifier: NSGregorianCalendar) let dateStr = formatter.stringFromDate(date) return dateStr } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}

最后你大概能够看到这种效果:

Swift 书面 ToDo App

5、最后一步,为待做项目加入通知功能,这一功能在之前的文章(ios8 notifacation in swift)中就讲过了,这里就不反复写了。完整的项目代码我发在github上来。须要的到这里拿。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/117472.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 超详细!Vue-Router手把手教程

    超详细!Vue-Router手把手教程(目录)最近在重温vue全家桶,再看一遍感觉记忆更深刻,所以专门记录一下(本文vue-router版本为v3.x)。1,router-view<router-view>是一个功能性组

    2022年7月4日
    18
  • IntentService原理

    IntentService的Demo程序IntentService常被用于处理异步任务,使用的步骤是,先继承IntentService,再在handleIntent方法里写业务逻辑。handleIntent是在子线程执行的,所以不必担心ANR之类的问题,可以执行IO操作,下载等操作,且当执行完后会自动销毁,很方便。先写一个简单的Demo。CountService.java:publicc…

    2022年4月6日
    37
  • Let’s Encrypt 申请HTTPS证书流程「建议收藏」

    Let’s Encrypt 申请HTTPS证书流程「建议收藏」准备工作:域名可供解析的服务器(或使用ngrok将需要生成证书的域名映射到具体的http服务器地址)申请官网地址:Let’sEncrypt、Certbot流程打开Certbot网址,选择使用服务器与操作系统,如下:使用如上命令在对应服务器安装好certbot后,使用:sudocertbotcertonly命令安装,certbot(实际上是certbot-au…

    2022年9月1日
    0
  • VMware虚拟机安装黑群晖7.0教程

    VMware虚拟机安装黑群晖7.0教程教程仅供参考,不当之处多多理解。该篇教程主要讲解黑群晖(DS918+)的安装Tip:本教程本教程只用于个人学习使用,有条件,长期使用的朋友推荐从正规官方渠道入手。1.首先安装VMware虚拟机双击安装文件进行安装…

    2022年7月14日
    194
  • Activity工作流引擎学习笔记(二)

    Activity工作流引擎学习笔记(二)核心APIProcessEngine说明:1) 在Activiti中最核心的类,其他的类都是由他而来。2) 产生方式:在前面看到了两种创建ProcessEngine(流程引擎)的方式,而这里要简化很多,调用ProcessEngines的getDefaultProceeEngine方法时会自动加载classpath下名为activiti.cfg.xml文件。3) 可以产生R

    2022年7月11日
    19
  • 远程桌面命令是什么 如何使用命令连接远程桌面

    远程桌面命令是什么 如何使用命令连接远程桌面

    2021年9月23日
    84

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号