我有一个子类的子视图中有一个textField。现在,我想在原始视图中调用textField的委托方法。
我用这段代码尝试了一下,但是不知何故方法没有被调用:
NewImageViewController *ni = [[NewImageViewController alloc] init];
textField.delegate = ni;
“ NewImageViewController”是我的原始视图。
编辑:
我的Subclass.h:
#import <UIKit/UIKit.h>
@protocol SubviewProtocol<NSObject>
- (void) textFieldDidEndEditing:(UITextField *)inTextField;
- (void) textFieldDidBeginEditing:(UITextField *)inTextField;
@end
@interface PopOverViewController : UIViewController <FPPopoverControllerDelegate>
@property (strong, nonatomic) UITextField *textField;
@property (nonatomic, assign) id<SubviewProtocol> delegate;
@end
Subview.m中的viewDidLoad:
textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 170, 30)];
textField.placeholder = @"Example";
textField.backgroundColor = [UIColor whiteColor];
textField.alpha = 0.9;
textField.borderStyle = UITextBorderStyleLine;
textField.layer.borderColor = [[UIColor grayColor]CGColor];
textField.textColor = [UIColor blackColor];
textField.delegate = self;
[self.view addSubview:textField];
NewImageViewController.m中的委托方法:
-(void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(@"asd");
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
NSLog(@"fgh");
}
最佳答案
由于您正在将UITextField作为子视图的属性
就是这样
我正在发布与您的案例相似的示例代码
希望它可以帮助您就可以解决这个问题
#import "SubView.h"
@implementation SubView
@synthesize aTextField;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UITextField *atextField = [[UITextField alloc]initWithFrame:CGRectZero];
self.aTextField = atextField;
[self addSubview:atextField];
[atextField release];
}
return self;
}
-(void)dealloc{
[self.aTextField release];
[super dealloc];
}
//i am setting the frame hear
-(void)layoutSubviews
{
self.aTextField.frame = CGRectMake(20,30, 100, 45);
}
@end
// in your main view
#import "ViewController.h"
#import "SubView.h"
@interface ViewController ()<UITextFieldDelegate> // add this
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//see below lines carfully
SubView *subView = [[SubView alloc]initWithFrame:self.view.frame];
subView.aTextField.delegate = self; // you need do this
subView.aTextField.placeholder = @"type hear";
subView.aTextField.backgroundColor = [UIColor greenColor];
[self.view addSubview:subView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//check out in main view
-(void) textFieldDidEndEditing:(UITextField *)inTextField
{
NSLog(@"textField end editing");
}
- (void) textFieldDidBeginEditing:(UITextField *)inTextField
{
NSLog(@"textField begin editing");
}
@end