Advanced Concepts
iOS Subclassing and conforming to protocols
Extending iOS classes β
The following example shows how to extend the UIViewController
:
constMyViewController= UIViewController.extend(
{
// Override an existing method from the base class.
// We will obtain the method signature from the protocol.
viewDidLoad: function () {
// Call super using the prototype:
UIViewController.prototype.viewDidLoad.apply(this, arguments)
// or the super property:
this.super.viewDidLoad()
// Add UI to the view here...
},
shouldAutorotate: function () {
returnfalse
},
// You can override existing properties
getmodalInPopover() {
returnthis.super.modalInPopover
},
setmodalInPopover(x) {
this.super.modalInPopover = x
},
// Additional JavaScript instance methods or properties that are not accessible from Objective-C code.
myMethod: function () {},
getmyProperty() {
returntrue
},
setmyProperty(x) {},
},
{
name: 'MyViewController',
},
)
The NativeScript runtime adds the .extend
API, as an option, which is available on any platform native class which takes an object containing platform implementations (classMembers
) for that class and an optional second argument object defining a nativeSignature
explained below.
You can also use the @NativeClass()
decorator with standard class extends
which may feel a bit more natural.
When creating custom platform native classes which extend others, always make sure their name is unique to avoid class name collisions with others on the system.
@NativeClass()
classJSObjectextendsNSObjectimplementsNSCoding {
publicencodeWithCoder(aCoder) {
/* ... */
}
publicinitWithCoder(aDecoder) {
/* ... */
}
public'selectorWithX:andY:'(x, y) {
/* ... */
}
// An array of protocols to be implemented by the native class
publicstaticObjCProtocols= [NSCoding]
// A selector will be exposed so it can be called from native.
publicstaticObjCExposedMethods= {
'selectorWithX:andY:': {
returns: interop.types.void,
params: [interop.types.id, interop.types.id],
},
}
}
Note
There should be no TypeScript constructor, because it will not be executed. Instead override one of the init
methods.
Exposed Method Example β
As shown above, extending native classes in NativeScript take the following form:
const <DerivedClass> = <BaseClass>.extend(classMembers, nativeSignature);
The classMembers
object can contain three types of methods:
- base class overrides,
- native visible methods, and
- pure JavaScript methods
The pure JavaScript methods are not accessible to native libraries. If you want the method to be visible and callable from the native libraries, pass the nativeSignature
parameter the needed additional metadata about the method signature to extend
with needed additional metadata about the method signature.
The nativeSignature
argument is optional and has the following properties:
name
- optional, string with the derived class nameprotocols
- optional, array with the implemented protocolsexposedMethods
- optional, dictionary with methodnames
andnative method signature
objects
The native method signature
object has two properties:
returns
- required,type
objectparams
- required, an array oftype
objects
The type object in general is one of the runtime types
:
- A constructor function, that identifies the Objective-C class
- A primitive types in the
interop.types
object - In rare cases can be a reference type, struct type etc. described with the interop API
The following example is how you can expose a pure JavaScript method to Objective-C APIs:
constMyViewController= UIViewController.extend(
{
viewDidLoad: function () {
// ...
constaboutButton= UIButton.buttonWithType(
UIButtonType.UIButtonTypeRoundedRect,
)
// Pass this target and the aboutTap selector for touch up callback.
aboutButton.addTargetActionForControlEvents(
this,
'aboutTap',
UIControlEvents.UIControlEventTouchUpInside,
)
// ...
},
// The aboutTap is a JavaScript method that will be accessible from Objective-C.
aboutTap: function (sender) {
constalertWindow=newUIAlertView()
alertWindow.title ='About'
alertWindow.addButtonWithTitle('OK')
alertWindow.show()
},
},
{
name: 'MyViewController',
exposedMethods: {
// Declare the signature of the aboutTap. We can not infer it, since it is not inherited from base class or protocol.
aboutTap: { returns: interop.types.void, params: [UIControl] },
},
},
)
Overriding Initializers β
Initializers should always return a reference to the object itself, and if it cannot be initialized, it should return null
. This is why we need to check if self
exists before trying to use it.
constMyObject= NSObject.extend({
init: function () {
constself=this.super.init()
if (self) {
// The base class initialized successfully
console.log('Initialized')
}
return self
},
})
Conforming to Objective-C/Swift protocols β
The following example conforms to the UIApplicationDelegate
protocol:
constMyAppDelegate= UIResponder.extend(
{
// Implement a method from UIApplicationDelegate.
// We will obtain the method signature from the protocol.
applicationDidFinishLaunchingWithOptions: function (
application,
launchOptions,
) {
this._window =newUIWindow(UIScreen.mainScreen.bounds)
this._window.rootViewController = MyViewController.alloc().init()
this._window.makeKeyAndVisible()
returntrue
},
},
{
// The name for the registered Objective-C class.
name: 'MyAppDelegate',
// Declare that the native Objective-C class will implement the UIApplicationDelegate Objective-C protocol.
protocols: [UIApplicationDelegate],
},
)
Let's look how to declare a delegate in Typescript by setting one for the Tesseract-OCR-iOS API
interfaceG8TesseractDelegateextendsNSObjectProtocol {
preprocessedImageForTesseractSourceImage?(
tesseract:G8Tesseract,
sourceImage:UIImage,
):UIImage
progressImageRecognitionForTesseract?(tesseract:G8Tesseract):void
shouldCancelImageRecognitionForTesseract?(tesseract:G8Tesseract):boolean
}
Implementing the delegate:
// native delegates often always extend NSObject
// when in doubt, extend NSObject
@NativeClass()
classG8TesseractDelegateImplextendsNSObjectimplementsG8TesseractDelegate {
staticObjCProtocols= [G8TesseractDelegate] // define our native protocols
staticnew():G8TesseractDelegateImpl {
return <G8TesseractDelegateImpl>super.new() // calls new() on the NSObject
}
preprocessedImageForTesseractSourceImage(
tesseract:G8Tesseract,
sourceImage:UIImage,
):UIImage {
console.info('preprocessedImageForTesseractSourceImage')
return sourceImage
}
progressImageRecognitionForTesseract(tesseract:G8Tesseract) {
console.info('progressImageRecognitionForTesseract')
}
shouldCancelImageRecognitionForTesseract(tesseract:G8Tesseract):boolean {
console.info('shouldCancelImageRecognitionForTesseract')
returnfalse
}
}
Using the class conforming to the G8TesseractDelegate
:
let delegate:G8TesseractDelegateImpl
functionimage2text(image:UIImage):string {
let tess:G8Tesseract= G8Tesseract.new()
// The `tess.delegate` property is weak and won't be retained by the Objective-C runtime so you should manually keep the delegate JS object alive as long the tessaract instance is alive
delegate = G8TesseractDelegateImpl.new()
tess.delegate = delegate
tess.image = image
let results:boolean= tess.recognize()
if (results ==true) {
return tess.recognizedText
} else {
return'ERROR'
}
}
Limitations β
- You should not extend an already extended class
- You can't override static methods or properties
- You can't expose static methods or properties
- Previous
- Android
Contributors
Last updated: