iOS loadNibNamed confusion, what is best practice?

前端 未结 3 1332
野的像风
野的像风 2020-12-14 02:08

I\'m familiar with most of the process of creating an XIB for my own UIView subclass, but not everything is working properly for me - it\'s mostly to do with the IBOutlets l

3条回答
  •  [愿得一人]
    2020-12-14 03:01

    Here's one method that I use:

    1. Create a subclass for UIView, this will be called MyClass
    2. Create a view xib file. Open in interface builder, click File's Owner and in the Identity Inspector, change the class to that of your parent view controller, e.g. ParentViewController.
    3. Click the view already in the list of objects and change it's class in Identity Inspector to MyClass.
    4. Any outlets/actions that you declare in MyClass will be connected by click-dragging from View (not File's Owner). If you want to connect them to variables from ParentViewController then click-drag from File's Owner.
    5. Now in your ParentViewController you need to declare an instance variable for MyClass.

    ParentViewController.h add the following:

    @class MyClass
    
    @interface ParentViewController : UIViewController {
        MyClass *myClass;
    }
    
    @property (strong, nonatomic) MyClass *myClass;
    

    Synthesize this in your implementation and add the following in your viewDidLoad method:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        [[NSBundle mainBundle] loadNibNamed:@"MyClass" owner:self options:nil];
        self.myClass.frame = CGRectMake(X,Y,W,H); //put your values in.
        [self.view addSubview:self.myClass];
    }
    

提交回复
热议问题