1. 程式人生 > 實用技巧 >UI基礎 屬性代理傳值

UI基礎 屬性代理傳值

rootview.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface RootViewController : UIViewController

@end

rootview.m

#import "RootViewController.h"
#import "SecondViewController.h"
@interface RootViewController ()<ChuanZhiDelegate>
{
    UITextField *tf;
    
}
@end

@implementation
RootViewController - (void)viewDidLoad { [super viewDidLoad]; // UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; // // view.backgroundColor=[UIColor redColor]; // [self.view addSubview:view]; // //把控制導航欄內容程式碼寫到對應的頁面上來 self.navigationItem.title=@"首頁"; // self.navigationItem.titleView=
//左右側的按鈕 文字 // self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"右側" style:UIBarButtonItemStylePlain target:self action:@selector(touchRight)]; // 圖片 self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Processsettings"] style:UIBarButtonItemStylePlain target:self action:@selector(touchRight)];
// 第一個頁面中的輸入框 頁面填充框 tf =[[UITextField alloc]initWithFrame:CGRectMake(20, 200, 280, 40)]; tf.backgroundColor=[UIColor greenColor]; [self.view addSubview:tf]; } -(void)Chaunzhi:(NSString *)str { NSLog(@"驗證有沒有傳值成功%@",str); } -(void)touchRight { NSLog(@"右側"); SecondViewController *second =[[SecondViewController alloc]init]; //傳值 second.inpurStr=tf.text; second.delegate=self; //跳轉 [self.navigationController pushViewController:second animated:YES]; } @end

secondview.h

#import <UIKit/UIKit.h>


//1.協議的名稱 宣告協議
@protocol ChuanZhiDelegate <NSObject>

-(void)Chaunzhi:(NSString *)str;

@end

NS_ASSUME_NONNULL_BEGIN

@interface SecondViewController : UIViewController

//宣告一個屬性用來接收傳遞過來的值
@property(nonatomic,strong)NSString *inpurStr;

//第二步 宣告屬性 (代理人)
@property(nonatomic,assign)id<ChuanZhiDelegate>delegate;


@end

secondview.m

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor greenColor];
    
//    第二個頁面左上角返回按鈕
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    
    //第二個頁面中的label
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(20, 200, 280, 40)];
    label.backgroundColor=[UIColor greenColor];
    
    label.text=self.inpurStr;
    
    [self.view addSubview:label];
}

-(void)goBack
{
    //返回的時候觸發方法 將值傳遞回去
    [self.delegate Chaunzhi:@"這個是要返回的值"];
    
//    從哪裡回到上一個
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

@end