点击uitextfield并崩溃

时间:2014-05-22 10:55:15

标签: ios objective-c uitextfield

我有两个UIViewController类。(名称: RootViewController & SecondViewController

我使用以下代码在FirstViewController中添加SecondViewController:

SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
[self.view addSubview:secondView.view];

所以我在SecondViewController中用代码创建了一个UITextField:

@interface SecondViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic,strong) UITextField *text1;
@end

@implementation SecondViewController
@synthesize text1;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    self.view.frame = CGRectMake(0, 200, 320, 300);

    text1 = [[UITextField alloc] initWithFrame:CGRectMake(20,70,180, 32)];
    text1.textAlignment = NSTextAlignmentRight;
    text1.layer.borderWidth = 1.0f;
    text1.layer.borderColor = [[UIColor grayColor] CGColor];
    text1.autocorrectionType = UITextAutocorrectionTypeNo;
    text1.delegate = self;
    [self.view addSubview:text1];
}
- (IBAction)BackgroundTap:(id)sender {
    [text1 resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [text1 resignFirstResponder];
    return YES;
}

现在我的问题在这里:当运行应用程序并点击我的文本域应用程序崩溃!为什么??? 当app崩溃时显示我的代码:

#import <UIKit/UIKit.h>

#import "AppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

这是我的错误:

enter image description here

1 个答案:

答案 0 :(得分:4)

您的视图控制器包含操作不正确:

SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController"
                                                                         bundle:nil];
[self addChildViewController:secondView]; //Assuming self is view controller
[self.view addSubview:secondView.view];
[secondView didMoveToParentViewController:self];

此处有更多信息:http://www.objc.io/issue-1/containment-view-controller.html