1.ios里面传值的方式很多中现在介绍几种常用的传值方式:
第一种: 属性传值方式:
首先要建两个controller 分别为 RootviewController和 DetailviewController
在Detailviewcontrooler.h实现的代码:(暴露出属性)
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property (nonatomic,copy)NSString *textString;//属性传值
@end
在Detailviewcontroller.m里面的实现代码:
@interface DetailViewController ()
@end
@implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
//添加一个返回按钮
UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(15,30 , 60, 30)];
[backBtn addTarget:self action:@selector(BACK) forControlEvents:UIControlEventTouchUpInside];
[backBtn setTitle:@"返回" forState:UIControlStateNormal];
[self.view addSubview:backBtn];
//创建一个label,来接收传过来的数值
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, 100, 30)];
label.textColor = [UIColor redColor];
label.backgroundColor = [UIColor grayColor];
label.textAlignment = NSTextAlignmentCenter;//对齐的方式
label.numberOfLines = 0; //不分行数
label.text = self.textString;//传值过来
[self.view addSubview:label];
}
-(void)BACK {
[self dismissViewControllerAnimated:NO completion:nil];
}
在Rootviewcontroller.m 的实现代码:
#import "RootViewController.h"
#import "DetailViewController.h"
@interface RootViewController ()
@property (nonatomic,retain)UITextField *textfield;
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.textfield = [[UITextField alloc]initWithFrame:CGRectMake(100, 30, 100, 30)];
self.textfield.backgroundColor = [UIColor grayColor];
self.textfield.layer.cornerRadius = 10.0;
[self.view addSubview:self.textfield];
//创建一个button传递事件
UIButton *custombutton = [[UIButton alloc]init];
custombutton.frame = CGRectMake(110, 100,80, 40);
[custombutton setTitle:@"入栈显示" forState:UIControlStateNormal ];
[custombutton addTarget:self action:@selector(handTap:) forControlEvents:UIControlEventTouchUpInside];
custombutton.backgroundColor = [UIColor redColor];
custombutton.layer.cornerRadius = 10.0;
[self.view addSubview:custombutton];
}
-(void)handTap:(UIButton *)sender{
DetailViewController *detailVC = [[DetailViewController alloc]init];
detailVC.textString = self.textfield.text;//后面的赋值给前面的
[self presentViewController:detailVC animated:NO completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
//点击空白处隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[self.view endEditing:YES]; //结束编辑
}
最后自己测试一下就可以成功了!!
第二种Block传值: 遇到问题了暂时没有上传代码了: