0

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

从主 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

如果有人知道或有任何想法可能出了什么问题,我很想听听!

4

2 回答 2

0

尝试更改您用于将 subvoew 添加到以下内容的代码:

- (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 时,实际上并没有调用任何初始化代码。

于 2013-05-22T21:10:12.863 回答
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];
}
于 2013-05-22T22:30:25.683 回答