子视图没有加载,但没有崩溃

时间:2013-05-22 20:58:28

标签: ios cocoa-touch uiview uiviewcontroller

所以我整天都在苦苦挣扎,试图让我的应用程序显示子视图。我没有收到任何错误或崩溃,但子视图没有显示出来。

从主ViewController调用子视图的代码(点击按钮时调用):

- (IBAction)SettingsButtonTapped:(id)sender {
  SettingsView *settings= [[SettingsView alloc]initWithFrame:CGRectMake(0,0,100,100)];
  //Thank you to Calman for fixing the init!
  [self.view addSubview:settings];
}

这是子视图.h文件:

#import <UIKit/UIKit.h>

@interface SettingsView : UIView
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *BackButton;

@end

和.m文件:

#import "SettingsView.h"
#import "ViewController.h"

@implementation SettingsView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
      NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
      NSString *name = [prefs stringForKey:@"name"];
      NSString *number = [prefs stringForKey:@"number"];
      username.tag=1;
      phoneNumber.tag=2;
      //if username is there
      if(name!=NULL)
      {
        username.text = name;
      }

      //if phone number is there
      if(number!=NULL)
      {
        phoneNumber.text=number;
      }

    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
@synthesize username;
@synthesize phoneNumber;

- (void)textFieldDidEndEditing:(UITextField *)textField
{
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  NSString *data=textField.text;
    if(textField.tag==1){
    //username was edited
    [prefs setObject:data forKey:@"name"];
  }
  else if (textField.tag==2){
    //phone number was edited
    [prefs setObject:data forKey:@"number"];
  }
}


@end

如果有人知道或有任何想法可能会出错,我很乐意听到!

2 个答案:

答案 0 :(得分:0)

尝试更改您用于将子视图添加到以下代码的代码:

- (IBAction)SettingsButtonTapped:(id)sender {
  SettingsView *settings= [[SettingsView alloc]initWithFrame:CGRectMake(0,0,100,100)]; //Change the CGRect to your appropriate origin and size
  [self.view addSubview:settings];
}

您目前正在做的是实例化没有框架的视图,因此即使您添加它,它也不可见。此外,当您只调用init时,实际上没有调用任何初始化代码。

答案 1 :(得分:0)

如果您正在使用xib文件,那么您使用的是错误的init方法。你需要像这样加载笔尖:

- (IBAction)SettingsButtonTapped:(id)sender {

  UINib *nib = [UINib nibWithNibName:@"SettingsView" bundle:nil];
  SettingsView *settings= [nib instantiateWithOwner:self options:nil][0];
  [self.view addSubview:settings];
}