iOS 视图之间的各种传值方式

2024-06-24 00:08
文章标签 方式 传值 ios 之间 视图

本文主要是介绍iOS 视图之间的各种传值方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

属性传值 将A页面所拥有的信息通过属性传递到B页面使用

B页面定义了一个naviTitle属性,在A页面中直接通过属性赋值将A页面中的值传到B页面。


A页面DetailViewController.h文件

#import <UIKit/UIKit.h>

#import "DetailViewController.h"

@interface RootViewController :UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end


A RootViewController.m页面实现文件

#import "RootViewController.h"

#import "DetailViewController.h"


@interface RootViewController ()

@end

@implementation RootViewController

//核心代码

-(void)loadView

{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

    tf = (UITextField *)[self.viewviewWithTag:1000];

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    

    DetailViewController *detailViewController = [[DetailViewControlleralloc]init];

    //属性传值,直接属性赋值

    detailViewController.naviTitle =tf.text;

    //导航push到下一个页面

    [self.navigationControllerpushViewController:detailViewController animated:YES];

    [detailViewControllerrelease];   

}


B页面DetailViewController.h文件

#import <UIKit/UIKit.h>

@interface DetailViewController :UIViewController

{

   UITextField *textField;

   NSString *_naviTitle;

}

@property(nonatomic,retain)NSString *naviTitle;

@end


B页面.m实现文件

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

@synthesize naviTitle =_naviTitle;

-(void)loadView

{

    self.view = [[[UIViewalloc]initWithFrame:CGRectMake(0,0320,480)]autorelease];

   self.title = self.naviTitle ;    

}


代理传值 

A页面push到B页面,如果B页面的信息想回传(回调)到A页面,用用代理传值,其中B定义协议和声明代理,A确认并实现代理,A作为B的代理

A页面RootViewController.h文件

#import <UIKit/UIKit.h>

#import "DetailViewController.h"

@interface RootViewController : UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end


A页面RootViewController.m实现文件

#import "RootViewController.h"

#import "DetailViewController.h"


@interface RootViewController ()

@end

@implementation RootViewController

//核心代码

-(void)loadView

{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    //A页面push到B页面

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

    tf = (UITextField *)[self.view viewWithTag:1000];

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    DetailViewController *detailViewController = [[DetailViewController alloc]init]; 

     //代理传值

   detailViewController.delegate =self;//让其自身作为代理人

    //导航push到下一个页面

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];   

}

//实现代理方法

-(void)changeTitle:(NSString *)aStr

{

    tf = (UITextField *)[self.view viewWithTag:1000];

    tf.text = aStr;//将从B页面传入的参数赋给A页面中的TextField

   tf.text = aStr;

}

B页面DetailViewController.m文件

#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController

{

    UITextField *textField;

    //定义代理

  id<ChangeDelegate>_delegate;

}

@property(nonatomic,assign)id<ChangeDelegate> delegate;

@end

//定义协议

@protocol ChangeDelegate <NSObject>

-(void)changeTitle:(NSString *)aStr;//协议方法

@end



B页面DetailViewController.h实现文件

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

-(void)loadView

{

    self.view = [[[UIView alloc]initWithFrame:CGRectMake(00320480)]autorelease];

    UIBarButtonItem *doneItem = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:selfaction:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItemrelease];

}

//pop回前一个页面

-(void)doneAction:(id)sender

{

   if (self.delegate && [self.delegaterespondsToSelector:@selector(changeTitle:)])//若代理存在且响应了changeTitle这个方法

    {

        //[self.delegate changeTitle:textField.text];

        [self.delegatechangeTitle:textField.text];//textField.text参数传给changeTitle方法  让代理,也就是A页面去实现这个方法

        NSLog(@"%@",self.navigationController.viewControllers);

        [self.navigationControllerpopViewControllerAnimated:YES];

    }

}



单例传值(实现共享)


AppStatus.h  创建一个单例类 AppStatus

#import <Foundation/Foundation.h>


@interface AppStatus : NSObject

{

    NSString *_contextStr;

}

@property(nonatomic,retain)NSString *contextStr;
 

+(AppStatus *)shareInstance;


@end

AppStatus.m 
 

#import "AppStatus.h"


@implementation AppStatus

@synthesize contextStr = _contextStr;


static AppStatus *_instance = nil;

+(AppStatus *)shareInstance

{

    if (_instance == nil)

    {

        _instance = [[super alloc]init];

    }

    return _instance;

}


-(id)init

{

    if (self = [super init])

    {

        

    }

    return  self;

}


-(void)dealloc

{

    [super dealloc];

}


@end


A页面RootViewController.h


#import 
"RootViewController.h"

#import "DetailViewController.h"

#import "AppStatus.h"


@interface RootViewController ()


@end


@implementation RootViewController

-(void)loadView

{
    //核心代码 

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0010030);

    [btn setTitle:@"Push" forState:0];

    [btn addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

}

-(void)pushAction:(id)sender

{

     

    tf = (UITextField *)[self.view viewWithTag:1000];

    

 //单例传值  将要传递的信息存入单例中(共享中)

  //  [[AppStatus shareInstance]setContextStr:tf.text]; 跟下面这种写法是等价的

    [AppStatus shareInstance].contextStr = tf.text;

    //导航push到下一个页面

    //pushViewController 入栈引用计数+1,且控制权归系统

    

    DetailViewController *detailViewController = [[DetailViewController alloc]init];

    

    //导航push到下一个页面

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];

} 
@end
 

B页面
DetailViewController.h


#import <UIKit/UIKit.h>

@protocol ChangeDelegate;//通知编译器有此代理


@interface DetailViewController : UIViewController

{

    UITextField *textField;

}

@end



B页面DetailViewController.m

#import "DetailViewController.h"

#import "AppStatus.h"


@interface DetailViewController ()


@end


@implementation DetailViewController

@synthesize naviTitle = _naviTitle;


-(void)loadView

{

    self.view = [[[UIView alloc]initWithFrame:CGRectMake(00320480)]autorelease];

    

    //单例

    self.title = [AppStatus shareInstance].contextStr;

    

    

    textField = [[UITextField alloc]initWithFrame:CGRectMake(10010015030)];

    textField.borderStyle = UITextBorderStyleLine;

    [self.view addSubview:textField];

    [textField release];


    UIBarButtonItem *doneItem = [[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:self action:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItem release];

    

}

//这个方法是执行多遍的  相当于刷新view

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    

    tf = (UITextField *)[self.view viewWithTag:1000];

    tf.text = [AppStatus shareInstance].contextStr;

     

}

//pop回前一个页面

-(void)doneAction:(id)sender

{

    //  单例传值

    [AppStatus shareInstance].contextStr = textField.text;

    [self.navigationController popToRootViewControllerAnimated:YES];

} 

 
通知传值 谁要监听值的变化,谁就注册通知  特别要注意,通知的接受者必须存在这一先决条件


A页面RootViewController.h

#import <UIKit/UIKit.h>

#import "DetailViewController.h"


@interface RootViewController : UIViewController<ChangeDelegate>

{

    UITextField *tf;

}

@end 
 

A页面RootViewController.m
 

#import "IndexViewController.h"

#import "DetailViewController.h"

#import "AppStatus.h"



@implementation IndexViewController


-(void)dealloc

{

    [[NSNotificationCenter defaultCenterremoveObserver:self

                                                    name:@"CHANGE_TITLE" object:nil];

    [super dealloc];

}


-(id)init

{

    if (self = [super init])

    {

        [[NSNotificationCenter defaultCenteraddObserver:self

                                                 selector:@selector(change:)

                                                     name:@"CHANGE_TITLE"

                                                   object:nil];

    }

    return self;

}


-(void)change:(NSNotification *)aNoti

{

    // 通知传值

    NSDictionary *dic = [aNoti userInfo];

    NSString *str = [dic valueForKey:@"Info"];

    

    

    UITextField *tf =  (UITextField *)[self.view viewWithTag:1000];

    tf.text = str;

}

 


-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    

    /*

    // 单例传值

    UITextField *tf =  (UITextField *)[self.view viewWithTag:1000];

    tf.text = [AppStatus shareInstance].contextStr;

    */

}

@end

DetailViewController.h
 

#import <UIKit/UIKit.h>

@protocol ChangeDelegate;//通知编译器有此代理


@interface DetailViewController : UIViewController

{

    UITextField *textField;

}

@end


 DetailViewController.m


#import "DetailViewController.h"

#import "AppStatus.h"



@implementation DetailViewController

@synthesize naviTitle = _naviTitle;


-(void)loadView

{

    

    UIBarButtonItem *doneItem = [[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemDonetarget:self action:@selector(doneAction:)];

    self.navigationItem.rightBarButtonItem = doneItem;

    [doneItem release];

}

// pop回前一个页面

-(void)doneAction:(id)sender

{

    

NSDictionary *dic = [NSDictionary dictionaryWithObject:textField.text forKey:@"Info"];


[[NSNotificationCenter defaultCenterpostNotificationName:@"CHANGE_TITLE" object:nil userInfo:dic];


[self.navigationController popViewControllerAnimated:YES];


}


Block

几种形式的Block

    //无返回值
    void (^block1) (void);
    block1 = ^{
        NSLog(@"bock demo");
    };
    block1();
    
    //int返回类型
    int (^block2) (void);
    block2  = ^(void)
    {
        int a  = 1 ,b =1;
        int c = a+b;
        return  c;
    };
    
    //有返回 有参数
    int (^block3)(int, int)= ^(int a, int b)
    {
        int c = a +b;
        return c;
        
    };
    NSLog(@"bock=%d",block3(1,2));
    
    //有返回值,有参数并且可以修改block之外变量的block
    static int sum = 10;// __blcik and static关键字 或者 _block int sum = 10
    int (^block4) (int) =^(int a)
    {
        sum=11;
        int c = sum+a;   //此时sum就是可以修改的了,若没加static或_block关键字则不能修改block之外变量
        return c;
    };
    NSLog(@"block4= %d",block4(4));


Block传值

例如A(Ablock)页面的值传道B(Bblock)页面  


在A页面中ABlock.h

@interface Ablock : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableview;
    UILabel *labe;
    UIImageView *imagevies;
}
@end


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableview deselectRowAtIndexPath:indexPath animated:YES];
    
    Bblcok *bblock = [[Bblcok alloc] initwithBlock:Block_copy(^(NSString *aBlock){    
        labe.text = aBlock;
        NSLog(@"%@",aBlock);

    })];
    

    bblock.imgeviews = imagevies.image;
    bblock.String = labe.text;
    [self.navigationController pushViewController:bblock animated:YES];
    [bblock release];
}



在A页面中Bblock.h

#import <UIKit/UIKit.h>
typedef  void (^MyBlock) (NSString *);
@interface Bblcok : UIViewController
{
    UIImageView *image;
    UITextField *aField;
    UIButton *aButt;
    NSString *_String;
    id _imgeviews;
    MyBlock myBlock;
}
@property(nonatomic,copy)MyBlock myBlock;   
@property(nonatomic,retain) id imgeviews;
@property(nonatomic,retain) NSString *String;
-(id)initwithBlock:(MyBlock)aBlcok;
@end


//
//  Bblcok.m
//  Blcok
//
//  Created by zhu  on 13-8-12.
//  Copyright (c) 2013年 Zhu Ji Fan. All rights reserved.
//

#import "Bblcok.h"

@interface Bblcok ()

@end

@implementation Bblcok
@synthesize imgeviews = _imgeviews , String = _String;
@synthesize myBlock = _myBlock;
-(id)initwithBlock:(MyBlock)aBlcok
{
    if (self = [super init])
    {
        self.myBlock = aBlcok; 
    }
    return self;
}

-(void) dealloc
{
    [super dealloc];
}

-(void) loadView
{
    UIControl *cont = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 568-44)];
    [cont addTarget:self action:@selector(Clcik) forControlEvents:UIControlEventTouchUpInside];
    self.view = cont;
    
    aField = [[UITextField alloc] initWithFrame:CGRectMake(60, 10, 160, 30)];
    aField.borderStyle = UITextBorderStyleLine;
    aField.placeholder = self.String;
    [self.view addSubview:aField];
    
    aButt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    aButt.frame = CGRectMake(60, 50, 70, 30);
    [aButt setTitle:@"修改" forState:0];
    [aButt addTarget:self action:@selector(aButtClcik:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:aButt];
    
    image = [[UIImageView alloc] initWithFrame:CGRectMake(60, 100, 210, 260)];
    image.backgroundColor = [UIColor blueColor];
    image.image = self.imgeviews;
    [self.view addSubview:image];
    [image release];

}

-(IBAction)aButtClcik:(id)sender
{
    NSString *sting = aField.text;
    myBlock(sting);
    [self.navigationController popToRootViewControllerAnimated:YES];
}


-(void)Clcik
{
    [aField resignFirstResponder];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

这篇关于iOS 视图之间的各种传值方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1088672

相关文章

MybatisPlus中几种条件构造器运用方式

《MybatisPlus中几种条件构造器运用方式》QueryWrapper是Mybatis-Plus提供的一个用于构建SQL查询条件的工具类,提供了各种方法如eq、ne、gt、ge、lt、le、lik... 目录版本介绍QueryWrapperLambdaQueryWrapperUpdateWrapperL

idea设置快捷键风格方式

《idea设置快捷键风格方式》在IntelliJIDEA中设置快捷键风格,打开IDEA,进入设置页面,选择Keymap,从Keymaps下拉列表中选择或复制想要的快捷键风格,点击Apply和OK即可使... 目录idea设www.chinasem.cn置快捷键风格按照以下步骤进行总结idea设置快捷键pyth

Linux镜像文件制作方式

《Linux镜像文件制作方式》本文介绍了Linux镜像文件制作的过程,包括确定磁盘空间布局、制作空白镜像文件、分区与格式化、复制引导分区和其他分区... 目录1.确定磁盘空间布局2.制作空白镜像文件3.分区与格式化1) 分区2) 格式化4.复制引导分区5.复制其它分区1) 挂载2) 复制bootfs分区3)

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流

java敏感词过滤的实现方式

《java敏感词过滤的实现方式》文章描述了如何搭建敏感词过滤系统来防御用户生成内容中的违规、广告或恶意言论,包括引入依赖、定义敏感词类、非敏感词类、替换词类和工具类等步骤,并指出资源文件应放在src/... 目录1.引入依赖2.定义自定义敏感词类3.定义自定义非敏感类4.定义自定义替换词类5.最后定义工具类

python项目环境切换的几种实现方式

《python项目环境切换的几种实现方式》本文主要介绍了python项目环境切换的几种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 如何在不同python项目中,安装不同的依赖2. 如何切换到不同项目的工作空间3.创建项目

SpringBoot的内嵌和外置tomcat的实现方式

《SpringBoot的内嵌和外置tomcat的实现方式》本文主要介绍了在SpringBoot中定制和修改Servlet容器的配置,包括内嵌式和外置式Servlet容器的配置方法,文中通过示例代码介绍... 目录1.内嵌如何定制和修改Servlet容器的相关配置注册Servlet三大组件Servlet注册详

C# WebAPI的几种返回类型方式

《C#WebAPI的几种返回类型方式》本文主要介绍了C#WebAPI的几种返回类型方式,包括直接返回指定类型、返回IActionResult实例和返回ActionResult,文中通过示例代码介绍的... 目录创建 Controller 和 Model 类在 Action 中返回 指定类型在 Action

SQL 注入攻击(SQL Injection)原理、利用方式与防御策略深度解析

《SQL注入攻击(SQLInjection)原理、利用方式与防御策略深度解析》本文将从SQL注入的基本原理、攻击方式、常见利用手法,到企业级防御方案进行全面讲解,以帮助开发者和安全人员更系统地理解... 目录一、前言二、SQL 注入攻击的基本概念三、SQL 注入常见类型分析1. 基于错误回显的注入(Erro

requests处理token鉴权接口和jsonpath使用方式

《requests处理token鉴权接口和jsonpath使用方式》文章介绍了如何使用requests库进行token鉴权接口的处理,包括登录提取token并保存,还详述了如何使用jsonpath表达... 目录requests处理token鉴权接口和jsonpath使用json数据提取工具总结reques