Storyboard and xib use in same project

2019-07-02 21:38发布

I am stumbling over what I believe is probably a fundamental misunderstanding of how classes work in Objective-C. I am using Storyboards but in this app I wanted to create a simple custom date picker view for a textfield on one of my view controllers. However, I seem to be having a problem accessing any of the properties of the date picker class from my view controller:

First I modeled my CustomDatePicker.xib in IB as follows:

enter image description here

I have created a custom class by sublcassing UIView as follows:

CustomPicker.h

@interface CustomPickerView : UIView

@property (strong, nonatomic) IBOutlet UIDatePicker* datePicker;

@end

CustomerPicker.m

@implementation CustomPickerView

- (id)init
{
    self = [super initWithFrame:CGRectMake(0, 0, 320, 258)];
    if (self) {
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"CustomPickerView" owner:self options:nil] objectAtIndex:0]];
    }
    return self;
}

In my ViewController:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.customPickerView=[[CustomPickerView alloc] init];

    // THE MAIN ISSUE IS...
    // Following line has no effect on how picker is presented ???
    self.customPickerView.datePicker.datePickerMode=UIDatePickerModeTime;

    self.dateField.inputView=self.customPickerView;
}

When the textfield is tapped, my CustomDatePicker pops up fine. However, I can't seem to set the .datePickerMode either from the viewDidLoad method of my ViewController. The only way I can change the .datePickerMode is through IB and of course that's not going to work at run-time.

I have wired up the outlet in IB and am able to access the datePicker.date from within the class but not the ViewController.

I have researched and viewed a number of ways to implement this concept. My question isn't how to implement a CustomDatePicker it is "Why can't I access properties of my CustomDatePicker from the ViewController that instantiated it?

2条回答
我只想做你的唯一
2楼-- · 2019-07-02 21:55
放我归山
3楼-- · 2019-07-02 22:05

I successfully changed the datePickerMode property when I loaded the NIB like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CustomPickerView" owner:self options:nil];
    self.customPickerView = (CustomPickerView *)[nibArray objectAtIndex:0];
    self.customPickerView.datePicker.datePickerMode = UIDatePickerModeTime;

    self.dateField.inputView = self.customPickerView;
}

And you can probably remove your custom view's init method altogether. I've never seen a NIB loaded in the init method like you're doing. While it might be possible, I believe that's what is causing your problem. Loading the NIB in viewDidLoad of the ViewController and setting it directly seems more straightforward.

查看更多
登录 后发表回答