iOS---简单的界面传值(属性传值,和协议方法)

第一种(属性传值)

正传是利用属性传值(例如,把第一个页面中TextFiled中的text传到第二个页面中的一个TextField的text中)

在第一个页面
ViewControllerFirst.h

@property UITextField *accounttextField;

ViewControllerFirst.m中

//一个Button的点击事件,跳转到第二个界面
-(void) pressToSecondViewController {
	SecondViewController *secondViewController = [[SecondViewController alloc] init];
	//用第二个页面中的NString *str属性进行接收
	registerViewController.str = _accounttextField.text;
	//跳转到第二个界面
	[self presentViewController:registerViewController animated:YES completion:nil];
}

SecondViewController.h中

@property NSString *str;  //用于接收
@property UITextField *accoutTextField;

在SecondViewController.m中

  _accoutTextField.text = _str; //进行赋值操作,将接收到的赋值给 _accoutTextField.text 

第二种 (协议传值)

(例如,将一个Account类,从SecondViewController传到ViewControllerFirst)
首先定义一个类Account,并且设置代理

#import <Foundation/Foundation.h>
@class Account;
NS_ASSUME_NONNULL_BEGIN
//设置代理
@protocol ZWYDelegate <NSObject>

//方法,传输account
-(void)pass:(Account *) account;

@end

@interface Account : NSObject
@property NSString *userNameString;
@property NSString *passWordString;
@end

NS_ASSUME_NONNULL_END码片

然后在ViewControllerFirst中,遵守协议方法

#import <UIKit/UIKit.h>
#import "Account.h"

@interface ViewController : UIViewController <UITextFieldDelegate,  ZWYDelegate>
@property NSMutableArray *accountArray;

在ViewControllerFirst.m中实现协议中的方法

//一个Button的点击事件,跳转到第二个界面
-(void) pressToSecondViewController {
	SecondViewController *secondViewController = [[SecondViewController alloc] init];
	//设置第二个界面的ZWYDelegate为第一个窗口的self
	secondViewController.zwyDelegate  = self;
	[self presentViewController:registerViewController animated:YES completion:nil];
}
//实现协议函数 这里是把,第二个页面中的account传回来,加入到一个数组当中
- (void)pass:(Account *)account {
    [_accountArray addObject:account];
}

在SecondViewController.h中

//用weak是防止循环引用
@property (nonatomic, weak)NSObject <ZWYDelegate> *zwyDelegate;

在SecondViewController.m 中

//在返回第一个页面的时候
-(void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
    //respondsToSelector是判断pass方法是否已经实现,如果实现进行传值操作
    if([self.zwyDelegate respondsToSelector:@selector(pass:)]) {
    	//通过委托协议传值
        [self.zwyDelegate pass:_accountAccount];
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值