如何从父swift 创建视图控制器器多次传递数据到Swift中的VC孩子

对于swift一直提不起来兴趣,老是不想学。。。前2周公司部门内需要做内部技术分享。这两周以来断断续续的看着,感觉真的是看起来真是没啥大的作用,除非真正的去用。才能发现一些问题。所以,大胆的去看文档吧,边看边实践,你会有不一样的收获的哦。
下面的这个例子呢,很简单,主要就是Swift下的UITableView的数据的展示以及数据增加删除,再就是通知,闭包,代理这三种传值方式,涉及到的知识点还是很多的,比如什么协议,扩展之类的,希望对初学者还是有点帮助的哈。
import UIKit
class ViewController: UIViewController{
var dataSourceArray = [[String:String]]()
var lyanlaTableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.configuerNavigarionView()
self.configuerView()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
func configuerNavigarionView(){
title = "演示Demo"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Done, target:self, action: Selector("next"))
func next(){
let inputVc = InputDetailViewController()
inputVc.lyanlaClosure = reloadTableViewData
navigationController?.pushViewController(inputVc, animated: true)
func configuerView(){
lyanlaTableView = UITableView(frame: CGRectMake(0, 20,view.frame.size.width, view.frame.size.height), style: UITableViewStyle.Plain)
lyanlaTableView.delegate = self
lyanlaTableView.dataSource = self
view.addSubview(lyanlaTableView)
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
lyanlaTableView.reloadData()
registerNotification(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadDataNotiy:", name:LyanlaNotification, object: nil)
func configureData(){
dataSourceArray.append(["title":"Wyy","content":"在很久很久以前,你拥有我,我拥有你"])
dataSourceArray.append(["title":"Mww","content":"每当夕阳西沉的时候"])
dataSourceArray.append(["title":"Qq","content":"天空虽然飘着雨,我依然等待你的归期"])
extension ViewController:UITableViewDataSource{
tableView datasource method
func numberOfSectionsInTableView(tableView: UITableView) -& Int{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -& Int{
return dataSourceArray.count
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -& UITableViewCell{
let cell = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel?.text = dataSourceArray[indexPath.row]["title"]
cell.detailTextLabel?.text = dataSourceArray[indexPath.row]["content"]
return cell
extension ViewController:UITableViewDelegate{
tableView delegate method
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -& CGFloat{
return 60.0
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
dataSourceArray .removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -& UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.Delete
extension ViewController:LyanlaPassValueDelegate{
func reloadDataNotiy(notification: NSNotification){
let dic = notification.object as! [String:String]
print(dic)
dataSourceArray.append(dic)
lyanlaTableView.reloadData()
实现代理方法以及闭包调用方法
func reloadTableViewData(string1:String,string2:String){
dataSourceArray.append(["title":string1,"content":string2])
lyanlaTableView.reloadData()
import UIKit
let LyanlaNotification:String = "ReloadDataNotification"
//委托代理模式
protocol LyanlaPassValueDelegate:NSObjectProtocol{
//回调方法
func reloadTableViewData(string1:String,string2:String)
typealias sendValueClosure = (string1:String,string2:String) -& Void
class InputDetailViewController: UIViewController,UITextFieldDelegate{
//声明一个代理
var delegate:LyanlaPassValueDelegate?
//声明一个闭包
var lyanlaClosure:sendValueClosure?
var inputText:String?
override func viewDidLoad() {
super.viewDidLoad()
self.configuerNavigarionView()
self.configuerView()
// 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.
func configuerNavigarionView(){
navigationItem.title = "输入"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target:self, action: Selector("save"))
func save(){
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let dateString = formatter.stringFromDate(date)
if (delegate) != nil{
//代理传值
delegate?.reloadTableViewData(inputText!,string2: dateString)
//闭包传值
if (lyanlaClosure != nil) {
print(inputText)
print(dateString)
lyanlaClosure!(string1: inputText!,string2: dateString)
//通知传值
NSNotificationCenter.defaultCenter().postNotificationName(LyanlaNotification, object: ["title":inputText!,"content":dateString])
navigationController?.popViewControllerAnimated(true)
func configuerView(){
view.backgroundColor = UIColor.whiteColor()
let inputView = UITextField(frame: CGRectMake(30, 100, view.frame.size.width-60, 40))
inputView.layer.borderColor = UIColor.redColor().CGColor
inputView.layer.borderWidth = 1
inputView.layer.cornerRadius = 6.0
inputView.placeholder = "请输入..."
inputView.delegate = self
view.addSubview(inputView)
func textFieldShouldReturn(textField: UITextField) -& Bool{
textField.resignFirstResponder()
inputText = textField.text
return true
运行起来的大致效果就是这样子的哈。
继续加油哈。哈哈哈
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:2902次
排名:千里之外2015年4月 移动开发大版内专家分月排行榜第二
2015年5月 移动开发大版内专家分月排行榜第三2015年3月 移动开发大版内专家分月排行榜第三2014年10月 移动开发大版内专家分月排行榜第三
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。iOS-UI界面设计(40)
我们先在这里约定:界面1传值到界面2为顺传,界面2传值到界面1为逆传
通知中心是一个单例,不管在哪个文件注册,也不管注册多少个,通知中心都是同一个。
一. 实现步骤
在界面2注册一个通知中心并指定通知名称,通知的信息就是要传递的数据,发布通知
在界面1注册一个通知中心,添加界面1为观察者,当有相同名字的通知时,就执行指定方法
在实现通知的方法中,进行赋值操作
在界面1中移除通知
二. 通知的优缺点
代码简洁,实现简单
一对多的方式,对于一个发出的通知,多个对象能够做出反应
控制器能通过通知传递context对象(dictionary),context对象携带了关于发送通知的自定义的信息
注:context对象:通俗的理解是一个公共的容器
在编译期不会检查通知是否能够被观察者正确的处理,应用的执行过程难跟踪
控制器发出通知后,不能从观察者获得任何的反馈信息
在释放注册的对象时,需要在通知中心取消注册
观察者需要提前知道通知名称和字典各个键名,如果这些不在工作区间内定义,那么会出现不同步的情况
三. 具体代码
1. AppDelegate类
---------- AppDelegate.m文件
#import "AppDelegate.h"
#include "OneViewController.h"
@interface AppDelegate ()
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *oneVc = [[OneViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:oneVc];
self.window.rootViewController =
[self.window makeKeyAndVisible];
nav.navigationBarHidden = YES;
return YES;
2. OneViewController类
---------- OneViewController.m文件
#import "OneViewController.h"
#import "TwoViewController.h"
@interface OneViewController ()
@property (nonatomic,strong) UITextField *textF
@implementation OneViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
clickBtn.frame = CGRectMake(10, 100, 80, 40);
clickBtn.backgroundColor = [UIColor whiteColor];
[clickBtn setTitle:@"到界面2" forState:UIControlStateNormal];
[clickBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[clickBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[clickBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clickBtn];
_textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 150, 250, 40)];
_textField.borderStyle = UITextBorderStyleRoundedR
_textField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_textField];
NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
[notification addObserver:self selector:@selector(changeValue:) name:@"passData" object:nil];
#pragma mark - 接收到通知后执行的方法
- (void)changeValue:(NSNotification *) notification {
_textField.text = [notification userInfo][@"info"];
#pragma mark - 点击事件
- (void)btnClick {
TwoViewController *twoVc = [[TwoViewController alloc] init];
[self.navigationController pushViewController:twoVc animated:YES];
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
3. TwoViewController类
---------- TwoViewController.m文件
#import "TwoViewController.h"
@interface TwoViewController ()
@property (nonatomic,strong) UITextField *textF
@implementation TwoViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
clickBtn.frame = CGRectMake(10, 100, 80, 40);
clickBtn.backgroundColor = [UIColor whiteColor];
[clickBtn setTitle:@"传 值" forState:UIControlStateNormal];
[clickBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[clickBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[clickBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clickBtn];
_textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 150, 250, 40)];
_textField.borderStyle = UITextBorderStyleRoundedR
_textField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_textField];
#pragma mark - 点击事件
- (void)btnClick {
NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
[notification postNotificationName:@"passData" object:self userInfo:@{@"info":_textField.text}];
[self.navigationController popViewControllerAnimated:YES];
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:19373次
排名:千里之外
原创:67篇UIViewController、UINavigationController、UITabBarController,这三者里面的控制器切换的区别?
这三种controller里的切换方式是怎样的?网上有看到说presentViewcontroller是在当前视图上盖上一层模态视图。模态视图是什么?那push和tabbar的controller之间的切换又是怎样进行的?
最近在学习转场动画,搞不清楚转场动画是怎么实现的,我知道UIViewControllerAnimatedTransitioning这协议里可以自定义动画,但操作的都是两个controller里的View,那controller是怎么切换的?请高手赐教,万分感谢!!
UIViewController&是所有控制器的基类,UINavigationController,&UITabBarController&都是直接或间接继承自UIViewController.&只是它们在UIVIewController的基础上又扩展了自己的实现。
UINavigationController:&导航控制器,&它是一个容器控制器,自身实现了它包含的所有子控制器之间的转场。&pushViewController(压栈)&,popViewController(出栈)。可见导航控制器,它维护了一个控制器栈,控制器之间的关系也符合栈的特点“后进先出”。&早期的API我们无法定制导航控制器转场动画,而现在我们可以通过实现UIViewControllerAnimatedTransitioning协议来自定义导航控制器的转场动画。
UITabBarController:&标签控制器。&它也是一个容器控制器。tab标签间的切换也是在内部实现。
模态窗口:&以模态窗口的方式显示新的视图控制器,新视图控制器关闭前,用户无法与其他控制器进行交互
引用&1&楼&zhanglei5415&的回复:UIViewController&是所有控制器的基类,UINavigationController,&UITabBarController&都是直接或间接继承自UIViewController.&只是它们在UIVIewController的基础上又扩展了自己的实现。
UINavigationController:&导航控制器,&它是一个容器控制器,自身实现了它包含的所有子控制器之间的转场。&pushViewController(压栈)&,popViewController(出栈)。可见导航控制器,它维护了一个控制器栈,控制器之间的关系也符合栈的特点“后进先出”。&早期的API我们无法定制导航控制器转场动画,而现在我们可以通过实现UIViewControllerAnimatedTransitioning协议来自定义导航控制器的转场动画。
UITabBarController:&标签控制器。&它也是一个容器控制器。tab标签间的切换也是在内部实现。
模态窗口:&以模态窗口的方式显示新的视图控制器,新视图控制器关闭前,用户无法与其他控制器进行交互
版主辛苦了,这板块人似乎不多啊。
其实我也不明白,我用了UITabBarConntroller然后在tab1的页面上放个按钮,push到uiviewcontroller2上,但是下面的tabbar依旧在的。用什么跳转方式,可以跳转到viewcontroller2上,而不是隐藏tabbar
即使是一小步也想与你分享4528人阅读
ios开发(5)
第一种 代码块(oc)
1 新建一个swift文件(NSobject、view、controller等),代码如下
class switfBlock: UIView{
typealias testBlock = (String)-&()
var blo: testBlock?
func nameBlock()
self.blo!("fdasf fhjkasdf fajkfh")
override func drawRect(rect: CGRect) {
2.使用方式
switfBlocks = switfBlock()
switfBlocks.blo = {str in
print("fa:\(str)")
第二种 协议(oc)
1 新建一个swift文件(NSobject、view、controller等),代码如下
protocol swiftDelegateProtocol {
func testDelegate(str: String)
class swiftDelegate: UIView {
var delegatessde : swiftDelegateProtocol?
func namede()
delegatessde?.testDelegate("fdasf\(swiftShare.shareDlin.names)")
override func drawRect(rect: CGRect) {
class ViewController: UIViewController, swiftDelegateProtocol {
override func viewDidLoad() {
super.viewDidLoad()
swiftDelegates = swiftDelegate()
swiftDelegates.delegatessde = self
swiftDelegates .namede()
func testDelegate(str: String) {//调用协议
print("de:\(str)")
1 新建一个swift文件(NSobject、view、controller等),代码如下
class swiftNotification: UIView {
func resigerNotifi()
let notifi = NSNotificationCenter.defaultCenter()
notifi.addObserverForName("notifid", object: nil, queue: nil,usingBlock: { (notifis: NSNotification) in
print("no:\(notifi)")
})//方式一
let operationQueue = NSOperationQueue.mainQueue()
notifi.addObserverForName("notifiQu", object: nil, queue: operationQueue) { (notofis: NSNotification) in
print("noQ:\(notifi)")
notifi.addObserver(self, selector:#selector(self.notifiNmae(_:)), name: "nofiNmae", object: nil)
notifi.addObserver(self, selector:#selector(notifiNmae(_:)), name: "nofiNmae", object: nil)
func notifiNmae(notifis: NSNotification) {
let share = swiftShare.getdataShare2()
print("noN:\(notifis)+_\(share.names)")
deist{//消除
NSNotificationCenter.defaultCenter().removeObserver(self)//移除通知
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
2 使用方式
NSNotificationCenter.defaultCenter().postNotificationName(“notifid”, object: nil)//方式1
NSNotificationCenter.defaultCenter().postNotificationName(“notifiQu”, object: nil)//方式2
NSNotificationCenter.defaultCenter().postNotificationName(“nofiNmae”, object: nil)//方式3
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:37500次
排名:千里之外}

我要回帖

更多关于 swift 切换视图控制器 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信