加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 05:04:02 所属栏目:百科 来源:网络整理
导读:我正在为React Native iOS编写自定义视图. 基本上我必须使文本尽可能大(基于当前视图的视图).我通过重写reactSetFrame并更改框架来完成它.唯一的问题是视图的位置是错误的,这是一个截图: 似乎本地反应的“布局管理器”认为视图的高度为0. 这里的代码: - (v
我正在为React Native iOS编写自定义视图.

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

似乎本地反应的“布局管理器”认为视图的高度为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,69.197000000000017}}
2017-06-25 16:43:16.435 ABC[44836:6551225] react set frame {{0,0}}
2017-06-25 16:43:16.436 ABC[44836:6551225] new frame is {{0,85.996999999999986}}

我已经尝试再次使用新帧调用reactSetFrame,但它无法正常工作.有没有办法告诉React Native视图的大小是否已经改变?

所以我终于找到了办法做到这一点;基本上反应原生利用阴影视图来获取布局信息.所以我必须将此代码添加到我的经理
- (RCTShadowView *)shadowView
{
  return [FitTextShadowView new];
}

这基本上是告诉我的组件的阴影视图是什么.

然后我不得不改变Yoga使用的measure函数的实现来获得正确的高度:

@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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读