ios - React-Native:无法触发 native UIButton 触摸事件

标签 ios swift react-native

我正在将原生 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=0height=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/

相关文章:

ios - 让用户画矩形来选择一个区域

ios - com.apple.developer.icloud-container-identifiers 和 com.apple.developer.ubiquity-container-identifiers 之间的区别

ios - Xcode 8/swift 3 : Reset all variables to initial values

android - 在 react-native 中用连字符换行

ios - didMoveToParentViewController 和 willMoveToParentViewController

php - React native http post 得到 Json Parse 错误 : Unrecognized token '<'

ios - 罗盘和陀螺仪传感器融合 : between 0 and 360 degrees

iphone - 将浮点值从数组传递到坐标时出现异常

reactjs - 无法读取未定义的属性 'width' (style.width)

reactjs - 在 React 应用程序中通过 laravel-echo 创建和加入 websocket