Skip to content

Commit 7ce4b0c

Browse files
Saadnajmitido64
andauthored
docs: add explainer for gotchas with NSView based native components (microsoft#1904)
* [Docs] Add explainer for gotchas with NSView based native components * Apply suggestions from code review Co-authored-by: Tommy Nguyen <[email protected]> * Update WritingNativeComponents.md --------- Co-authored-by: Tommy Nguyen <[email protected]>
1 parent 060a80b commit 7ce4b0c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

docs/WritingNativeComponents.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Writing native components derived from NSView
2+
3+
4+
React Native macOS inherits some assumptions from React Native on iOS / UIKit. There are subtle differences in how AppKit's and UIKit's implementation, such as where the coordinate system places the origin (bottom left on Appkit, top left on UIKit), or how hit testing is implemented. This serves as an issue when we want to write our own native components derived from NSView, as we don't inherit the "fixes" made in RCTView to get views working properly. This doc illustrates what methods / implementation you will need to override in order for your native component, using the NSView derived `NSVisualEffectView` as our base class.
5+
6+
```Swift
7+
internal class FixedVisualEffectView: NSVisualEffectView {
8+
9+
/// React Native macOS uses a flipped coordinate space by default. to match the other platforms.
10+
/// Let's stay consistent and ensure any views hosting React Native views are also flipped.
11+
/// This helps RCTTouchHandler register clicks in the right location, and ensures `layer.geometryFlipped` is true.
12+
override var isFlipped: Bool {
13+
return true
14+
}
15+
16+
/// This subclass is necessary due to differences in hitTest()'s implementation between iOS and macOS
17+
/// On iOS / UIKit, hitTest(_ point:, with event:) takes a point in the receiver's local coordinate system.
18+
/// On macOS / AppKit, hitTest(_ point) takes a point in the reciever's superviews' coordinate system.
19+
/// RCTView assumes the iOS implementation, so it has an override of hitTest(_ point). Let's copy the
20+
/// implementatation to our native component, so that clicks for subviews of type RCTView are handled properly.
21+
/// Another solution would be to add an RCTView subview that covers the full bounds of our native view
22+
open override func hitTest(_ point: NSPoint) -> NSView? {
23+
var pointForHitTest = point
24+
for subview in subviews {
25+
if let subview = subview as? RCTView {
26+
pointForHitTest = subview.convert(point, from: superview)
27+
}
28+
let result = subview.hitTest(pointForHitTest)
29+
if (result != nil) {
30+
return result
31+
}
32+
}
33+
return nil
34+
}
35+
}
36+
```

0 commit comments

Comments
 (0)