How do I set a property on a custom view instantiated from a XIB

后端 未结 3 481
逝去的感伤
逝去的感伤 2021-01-29 01:22

I am just trying to get my head around MVC in Objective C and IOS but am having a problem I\'m hoping someone can help me with.

I have created a custom view (created as

相关标签:
3条回答
  • 2021-01-29 01:45

    Your custom view's properties (as opposed to its outlets) can only be set in code unless you create an IB plugin for it.

    Your other subviews can be accessed easily if you create an outlet for each of them in your controller. The view outlet is there as the primary view of that view controller. There is nothing preventing you creating additional outlets to other views/controls. Yu would just need to subclass the view controller and add the outlets as needed. Just remember to set the class name of the controller (in Interface Builder) to that of your custom subclass. That will expose the available outlets for you to connect.

    You'd still need to create an Interface Builder plugin if you want to make your control's custom properties available in IB's inspector palette. Unless you plan to reuse it frequently in other applications or make it available to others, it's probably easiest just to set the properties in your source code.

    0 讨论(0)
  • 2021-01-29 01:54

    You can just create another property on your view controller of type MyCustomView*.

    Declare that property as an IBOutlet and you wire that up in IB.

    Then in your view controller you can use that property to access that custom view.

    0 讨论(0)
  • 2021-01-29 02:08

    Example for setting corner radius of your custom subview (subclass of UIButton in my case) from xib.

    1. Create a property like this

      @property (nonatomic, assign) IBInspectable CGFloat cornerRadius;
      
    2. Override setter in your custom view's implementation file.

      -(void)setCornerRadius:(CGFloat)cornerRadius
      {
           self.layer.cornerRadius = cornerRadius;
      }
      
    3. Drag your view in xib and change its class to your custom class.enter image description here

    4. Magic... You will see the custom properties appearing in attribute inspector like this. enter image description here

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