When is the Register attribute needed in Xamarin.iOS apps?
-
20-12-2019 - |
Question
When exactly is the Register
attribute required in a Xamarin.iOS app?
I found an existing post that gives some explanation of what it does, but I'm not clear on when it's needed.
I've written a fairly extensive app without being forced to use Register
on any of my UIViewController
or UIView
subclasses.
In my case, I'm doing all of my layout from C# code, so no xib
files to be found. It sounds like one of the use cases for Register
is interacting with views created in Interface Builder.
Can someone shed some light on this?
Solution
Anytime ObjectiveC runtime needs to create an instance of the managed type it will need to be registered. If you create your custom views and controllers from code you don't have much, if any, need to use it. If you plan to create any reusable UI controls then you should register them so someone using layout editors can use them. Lets say you create a custom UIView called MyView and register it, you can drag an UIView control into a view controller in XCode and change its type to MyView instead of UIView. It still won't render in XCode editor but it will be created as MyView at runtime, otherwise it would be created as UIView.
OTHER TIPS
Any object that derives from NSObject will automatically be exported to Objective-C, technically there is no need for the [Register] attribute.
However the attribute is useful when you want the Objective-C name to be different than the default:
[Register ("MyObject")]
class MyCustomObject : NSObject
{
}
This would register the managed MyCustomObject
type with Objective-C using MyObject
as the native name.