比如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
2 回答

蕪湖不蕪
TA貢獻1796條經驗 獲得超7個贊
如果理解了delegate的意思,就知道如何使用delegate了。
簡單來說,就是某件事情發生了,我處理不了,需要借助外部力量才行。好比我要出遠門,走肯定不現實,這時就要借助交通工具,如:汽車、火車、飛機。只要這些交通工具都實現了某個協議,確保調用該交通工具的某個方法時不會出錯。
如果我主動去設置delegate,如:我.delegate = 火車。沒有錯,但沒什么意義,delegate的靈活性就不存在了,我被某個交通工具綁死了。所以 我.delegate 需要在外部設置。對我來說,只要在適當的時候執行 我.delegate.go 就行了。要是delegate是飛機就爽了,是一輛臨客就認了吧。
- 2 回答
- 0 關注
- 175 瀏覽
添加回答
舉報
0/150
提交
取消