我正在将原生 Swift 模块桥接到 React Native。我创建了一个 UIView
,它创建了一个带有目标处理程序的 UIButton
。它正确呈现所有内容,但是单击按钮不会触发任何内容。我在这里主持了一个演示:https://github.com/esbenp/react-native-swift-test
我的原生模块相当简单:https://github.com/esbenp/react-native-swift-test/blob/master/ios/TestModule.swift
let Button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
Button.setTitleColor(UIColor.blue, for: .normal)
Button.setTitle("Press me", for: .normal)
Button.addTarget(self, action: #selector(TestModule.onClick), for: .touchUpInside)
self.addSubview(Button)
我使用管理器桥接它:https://github.com/esbenp/react-native-swift-test/blob/master/ios/TestModuleManager.m
#import <React/RCTViewManager.h>
#import "ReactNativeSwiftTest-Swift.h"
@interface TestModuleManager : RCTViewManager
@end
@implementation TestModuleManager
RCT_EXPORT_MODULE()
- (UIView *)view
{
return [[Parent alloc] init];
}
@end
然后在 JS 中运行:https://github.com/esbenp/react-native-swift-test/blob/master/index.ios.js
我不是 iOS 专家,但它似乎与框架有关。如果我采用相同的 native 模块并在普通的 iOS 项目 UIViewController
中使用它,如下所示:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let Button = TestModule(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
self.view.addSubview(Button)
}
它有效。我假设这是因为 React Native 创建的框架是 width=0
和 height=0
(至少如果我 NSLog(String(describing : frame.size.height))
).
iOS MapView example指定不覆盖框架,因为 React Native 将设置它。我不知道框架是不是错了,还是我在这里遗漏了其他一些上下文?我尝试按照 #2948 #15097 中的说明进行操作,但没有任何帮助。
最佳答案
我在这里发现了错误。事实证明,您必须将 flex: 1
添加到 JS 端的实际 native 组件,以使框架正确填充。
之前
export default class ReactNativeSwiftTest extends Component {
render() {
return (
<View style={styles.container}>
<Test />
</View>
);
}
}
之后
export default class ReactNativeSwiftTest extends Component {
render() {
return (
<View style={styles.container}>
<Test style={{flex: 1}} />
</View>
);
}
}
关于ios - React-Native:无法触发 native UIButton 触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784224/