Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native dynamic-sized UI component for React Native

Tags:

react-native

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?

like image 351
aksonov Avatar asked Aug 06 '15 09:08

aksonov


1 Answers

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;
}
like image 76
aksonov Avatar answered Oct 23 '22 06:10

aksonov