比如A,B两个view,值从A传到B。
在B里面写
A *av = [[A alloc]init]; [av setDelegate:self]
和在A里面写
B *bv = [[B alloc]init]; [self setDelegate:bv];
这句setDelegate要放哪里呢?viewDidLoad?没有报错,但是就是传值不成功。能给我一点提示吗?
代码
#import <Foundation/Foundation.h> @protocol delegate <NSObject> -(void)passString:(NSString *)string; @end
#import <UIKit/UIKit.h> #import "labelViewController.h" #import "delegate.h" @interface buttonViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *button; @property (weak,nonatomic) id <delegate> delegate; - (IBAction)buttonPress:(UIButton *)sender; @end
#import "buttonViewController.h" @interface buttonViewController () @end @implementation buttonViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { labelViewController *lv = [[labelViewController alloc]init]; [self setDelegate:lv]; [super viewDidLoad]; // Do any additional setup after loading the view. } - (IBAction)buttonPress:(UIButton *)sender { [self.delegate passString:sender.currentTitle]; [self performSegueWithIdentifier:@"push" sender:self]; } @end
#import <UIKit/UIKit.h> #import "delegate.h" @interface labelViewController : UIViewController <delegate> @property (weak, nonatomic) IBOutlet UILabel *label; @end
#import "labelViewController.h" @interface labelViewController () @end @implementation labelViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)passString:(NSString *)string{ self.label.text = string; NSLog(@"%@",self.label.text); } @end
没太看明白问题什么意思。。。建议你把完整的需求和代码贴一下。你提供的两个代码片段,在不同情况下我都用过。。。都是可以的
先只能按照我的理解普及一下delegate的知识。
先解释一下delgate是什么东西,delgate直译过来叫代理。
作用举个例子:
在类A中实现控制类B的代码,把类B的实例属性delegate设成类A的实例。
了解了delegate的原理,再看你问题里的代码
是合理的,而另一种写法,把Delegate设成某个初始化的实例就比较诡异了(虽然我曾经有这么用过,但是是很特殊的情况)
补充再说viewDidLoad的问题,这个函数是在整个View初始化后,载入完成,调用的。一般就在这里赋值,初始化subviews。
有这么几个问题
1,delegate的类名尽量不要用保留字,看起来太诡异了
2,delegate的用法是,在LabelViewController里定义一个delegate实例,然后调用delegate的方法
3,实现delegate的应该是ButtonViewController
代码如下:
LabelViewController.h
LabelViewController.m
ButtonViewController.h
ButtonViewController.m