如何通知React Native自定义视图的大小已更改?

时间:2017-06-25 15:47:26

标签: react-native react-native-ios

我正在为React Native iOS编写自定义视图。

基本上我必须使文本尽可能大(基于当前视图的视图)。我是通过覆盖reactSetFrame并更改框架来完成的。唯一的问题是视图的位置是错误的,这是一个截图:

overlapping views

似乎本地反应的“布局管理器”认为视图的高度为0。

这里是代码:

- (void)reactSetFrame:(CGRect)frame {
  [super reactSetFrame:frame];

  NSLog(@"react set frame %@", NSStringFromCGRect(frame));

  [self fitText:self.text];
}

- (void)fitText:(NSString *)text {
    // ... get the correct font size and expected size    
    [self setFont:font];

    CGRect newFrame = self.frame;

    newFrame.size.height = expectedLabelSize.height;

    NSLog(@"new frame is %@", NSStringFromCGRect(newFrame));

    self.frame = newFrame;
}

基本上当框架发生变化时,我会根据传递的文本使用正确的尺寸更新框架。

日志输出为:

2017-06-25 16:43:16.434 ABC[44836:6551225] react set frame {{0, 0}, {375, 0}}
2017-06-25 16:43:16.435 ABC[44836:6551225] new frame is {{0, 0}, {375, 69.197000000000017}}
2017-06-25 16:43:16.435 ABC[44836:6551225] react set frame {{0, 0}, {375, 0}}
2017-06-25 16:43:16.436 ABC[44836:6551225] new frame is {{0, 0}, {375, 85.996999999999986}}

我尝试再次使用新框架调用reactSetFrame,但它无效。有没有办法告诉React Native视图的大小是否已经改变?

1 个答案:

答案 0 :(得分:3)

所以我终于找到了办法做到这一点;基本上反应原生利用阴影视图来获取布局信息。所以我必须将此代码添加到我的经理

- (RCTShadowView *)shadowView
{
  return [FitTextShadowView new];
}

基本上是告诉我的组件的阴影视图。

然后我不得不改变瑜伽使用的测量功能的实现来获得正确的高度:

@implementation FitTextShadowView

static YGSize RCTMeasure(YGNodeRef node, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode)
{
  FitTextShadowView *shadowText = (__bridge FitTextShadowView *)YGNodeGetContext(node);
  YGSize result;

  result.width = width;
  result.height = [shadowText getHeight:shadowText.text thatFits:width];
  return result;
}

- (instancetype)init
{
  if ((self = [super init])) {
    YGNodeSetMeasureFunc(self.yogaNode, RCTMeasure);
  }
  return self;
}

@end
相关问题