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

相关文章

如何突破底层思维方式的牢笼

我始终认为,牛人和普通人的根本区别在于思维方式的不同,而非知识多少、阅历多少。 在这个世界上总有一帮神一样的人物存在。就像读到的那句话:“人类就像是一条历史长河中的鱼,只有某几条鱼跳出河面,看到世界的法则,但是却无法改变,当那几条鱼中有跳上岸,进化了,改变河道流向,那样才能改变法则。”  最近一段时间一直在不断寻在内心的东西,同时也在不断的去反省和否定自己的一些思维模式,尝试重

idea lanyu方式激活

访问http://idea.lanyus.com/这个地址。根据提示将0.0.0.0 account.jetbrains.com添加到hosts文件中,hosts文件在C:\Windows\System32\drivers\etc目录下。点击获得注册码即可。

iOS HTTPS证书不受信任解决办法

之前开发App的时候服务端使用的是自签名的证书,导致iOS开发过程中调用HTTPS接口时,证书不被信任 - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAu

以canvas方式绘制粒子背景效果,感觉还可以

这个是看到项目中别人写好的,感觉这种写法效果还可以,就存留记录下 就是这种的背景效果。如果想改背景颜色可以通过canvas.js文件中的fillStyle值改。 附上demo下载地址。 https://download.csdn.net/download/u012138137/11249872

vue同页面多路由懒加载-及可能存在问题的解决方式

先上图,再解释 图一是多路由页面,图二是路由文件。从图一可以看出每个router-view对应的name都不一样。从图二可以看出层路由对应的组件加载方式要跟图一中的name相对应,并且图二的路由层在跟图一对应的页面中要加上components层,多一个s结尾,里面的的方法名就是图一路由的name值,里面还可以照样用懒加载的方式。 页面上其他的路由在路由文件中也跟图二是一样的写法。 附送可能存在

vue子路由回退后刷新页面方式

最近碰到一个小问题,页面中含有 <transition name="router-slid" mode="out-in"><router-view></router-view></transition> 作为子页面加载显示的地方。但是一般正常子路由通过 this.$router.go(-1) 返回到上一层原先的页面中。通过路由历史返回方式原本父页面想更新数据在created 跟mounted

MySQL数据库(四):视图和索引

在数据库管理中,视图和索引是两种关键工具,它们各自发挥独特的作用以优化数据查询和管理。视图通过简化复杂查询、提高数据安全性和提供数据抽象,帮助用户轻松访问数据。而索引则通过加速查询、确保数据唯一性以及优化排序和分组操作,显著提升数据库性能。理解和合理运用这两者,对数据库系统的高效运行至关重要。 目录 一、视图概念(面试) 二、视图的作用(面试) 三、视图的创建和使用 3.1

二叉树三种遍历方式及其实现

一、基本概念 每个结点最多有两棵子树,左子树和右子树,次序不可以颠倒。 性质: 1、非空二叉树的第n层上至多有2^(n-1)个元素。 2、深度为h的二叉树至多有2^h-1个结点。 3、对任何一棵二叉树T,如果其终端结点数(即叶子结点数)为n0,度为2的结点数为n2,则n0 = n2 + 1。 满二叉树:所有终端都在同一层次,且非终端结点的度数为2。 在满二叉树中若其深度为h,则其所包含

七种排序方式总结

/*2018.01.23*A:YUAN*T:其中排序算法:冒泡排序,简单排序,直接插入排序,希尔排序,堆排序,归并排序,快速排序*/#include <stdio.h>#include <math.h>#include <malloc.h>#define MAXSIZE 10000#define FALSE 0#define TRUE 1typedef struct {i

ccp之间是不可以直接进行+,-的,要用ccpSub和ccpAdd。

1.  http://www.cnblogs.com/buaashine/archive/2012/11/12/2765691.html  上面有好多的关于数学的方面的知识,cocos2dx可能会用到的 2.学到了   根据tilemap坐标得到层上物体的id int oneTiled=flagLayer->tileGIDt(tilePos);