React Native 的原生动态大小 UI 组件 [英] Native dynamic-sized UI component for React Native

查看:68
本文介绍了React Native 的原生动态大小 UI 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建 iOS React Native 组件 - Text 的模拟,其中宽度和高度未知,但根据其内容动态计算.正如我从调试中看到的,RCTText.drawRect 方法已经用计算出的矩形调用了,但是如果我没有通过样式定义大小,我的组件会用空矩形调用.

I want to build iOS react native component - analog of Text, where width and height is not known, but calculated dynamically depending from its content. As I see from debugging, RCTText.drawRect method is called with calculated rect already, but my component is called with empty rect if i did not define sizes via styles.

如何为自定义视图定义所需的矩形?

How to define needed rect for custom View?

推荐答案

答案在于阴影"视图概念.看起来没有记录,但 React Native 在实际渲染之前使用阴影"视图来计算布局.所以RCTShadowText类用于标签的布局及其RCTMeasure函数:

The answer is in 'shadow' view concept. It looks like not documented, but React Native uses 'shadow' views to calculate layout before actual rendering. So RCTShadowText class is used for layout of tag and its RCTMeasure function:

static css_dim_t RCTMeasure(void *context, float width)
{
  RCTShadowText *shadowText = (__bridge RCTShadowText *)context;
  NSTextStorage *textStorage = [shadowText buildTextStorageForWidth:width];
  NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
  NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
  CGSize computedSize = [layoutManager usedRectForTextContainer:textContainer].size;

  css_dim_t result;
  result.dimensions[CSS_WIDTH] = RCTCeilPixelValue(computedSize.width);
  if (shadowText->_effectiveLetterSpacing < 0) {
    result.dimensions[CSS_WIDTH] -= shadowText->_effectiveLetterSpacing;
  }
  result.dimensions[CSS_HEIGHT] = RCTCeilPixelValue(computedSize.height);
  return result;
}

这篇关于React Native 的原生动态大小 UI 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆