所以我整天都在挣扎,试图让一个子视图出现在我的应用程序上。我没有收到任何错误或崩溃,但子视图没有出现。
从主 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
如果有人知道或有任何想法可能出了什么问题,我很想听听!