Checklists学习日志之再看prepareForSegue方法的使用

之前写了一下prepareForSegue方法的使用,那时候只是大概知道怎么回事。这次来阐明一些更细节的数据传递的问题。

我门要从AllListsViewController跳转到ChecklistViewController,并向其传递数据。首先我们先在ChecklistViewController中定义接收数据的变量。这里用感叹号的原因是:nil is normally not an allowed value for variables in Swift but by using the ! you override that.  即viewDidLoad()被执行前,允许checklist为nil。

var checklist: Checklist! 

这里的Checklist!是我们在另一个文件Checklist.swift中定义的类,他具有name的属性。

import UIKit

class Checklist: NSObject {
    var name = ""
    init(name: String)
    {
        self.name = name
        // Because both the parameter and the instance variable are called name, you use self.name to refer to the instance variable. self.name=(var name = "")
        super.init()
    }

}

然后,在AllListsViewController中,我们使用prepareForSegue方法向ChecklistViewController传递数据

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //Tells the delegate that the specified row is now selected.
        let checklist = lists[indexPath.row]//
        performSegueWithIdentifier("ShowChecklist", sender: checklist)
        // 这个函数相当于在初始化segue,但此时segue还没有被传送给ChecklistViewController
        // 由于performSegueWithIdentifier是在tableView(didSelectRowAtIndexPath)函数里面调用的。所以,点击一行的操作执行之后,performSegueWithIdentifier将被调用
        // 从 Checklists Scene 跳转到 Name of the Checklist
        // Segue(Checklists Scene 到 Name of the Checklist的Segue名字叫ShowChecklist)
        // 点击一行的时候,这个method将被调用
        // The object that you want to use to initiate the segue.
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Notifies the view controller that a segue is about to be performed.

        if segue.identifier == "ShowChecklist"{
            let controller = segue.destinationViewController as! ChecklistViewController
            controller.checklist = sender as! Checklist
            // By writing “sender as! Checklist”, you tell Swift that it can safely treat sender as a Checklist object.
        }
    }

来解释一下这两个方法的内容。第一个是segue的初始化,并定义sender是一个常量checklist。注意,这里的checklist = lists[indexPath.row],说明checklist是一个Checklist类的常量。当点击一行的时候将被调用。第二个是正式的prepareForSegue。先判断segue.identifier是不是我们预先在故事版定义的值。然后令controller为destinationViewController,也就是我们要跳转到的ChecklistViewController。注意,这里的as告诉编译器,segue指向的是ChecklistViewController类的变量。然后,我们通过controller.checklist = sender as! Checklist,把sender的内容传递给ChecklistViewController。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值