confused difference between Custom Class for an Object and for the File's Owner and steps via IB

后端 未结 2 1437
灰色年华
灰色年华 2021-01-03 13:23

This is another \"I\'m confused question\". So I\'m working on bringing in custom views into a view controller. I\'ll just outline the exact steps for the error.

    <
相关标签:
2条回答
  • 2021-01-03 13:44

    Define an IBOutlet @property in your parent class's @interface section like this:

    @property (weak, nonatomic) IBOutlet ArcView *arcView
    

    Then go into Interface Builder, and right click on File's Owner. When you see "arcView" in the black HUD window, drag the mouse from that item to your view on the XIB.

    Now you have a property for your arcview control, and you can utilize it just like you would any control such as UIButton, UILabel etc.

    0 讨论(0)
  • 2021-01-03 13:44

    Set the file's owner == your UIView subclass so that you can connect outlets to it. And you should set the class of nib-painted UIView to that same subclass because it's an instance of that UIView subclass.

    In other words, follow these steps:

    1. create a UIView subclass called CustomView
    2. create a UIView xib New File -> User Interface -> View
    3. change the file's owner to CustomView
    4. change the view's class to CustomView
    5. add subviews if you wish, connect them as outlets to the files owner (CustomView)

    Your crash is happening because your code says this:

    UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"theNIB" owner:self options:nil] objectAtIndex:0];
    

    But that owner:self is the view controller where this code is running. You want the view subclass to be the nib's owner.

    To fix, give your UIView subclass the job of init-ing itself from the nib, like this:

    CustomView.h

    @interface CustomView : UIView
    
    - (id)initFromNib;
    
    @end
    

    CustomView.m

    #import "CustomView.h"
    
    @interface CustomView ()
    // connect this in the XIB to file's owner that you've set to this CustomView class
    @property (weak, nonatomic) IBOutlet UILabel *myLabel;
    @end
    
    @implementation CustomView
    
    - (id)initFromNib
    {
        self = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];
    
        if (self) {
            // prove you can set properties on your outlets
            self.myLabel.text = @"this is good";
        }
        return self;
    }
    

    I built a little project with just this stuff in it as described. Works fine. Lemme know if you'd like to see it and I'll find a way to send you an anonymous zip.

    0 讨论(0)
提交回复
热议问题