React Native: How to calculate custom native UITextView height dynamically

425 views Asked by At

I am working on an existing iOS-App in which I have added new features with React-Native. Works great so far. Now I have to use an already developed custom native Swift UITextView subclass. The text is getting fetched from the API. So the size of the UITextView should be dynamic.

On React-Native side it looks like this:

import { requireNativeComponent } from 'react-native';

export const NativeTextView = requireNativeComponent('RNNativeTextView');

export default function FooView(props: FooViewProps) {
    return (
        <View
            style={{
                ...props.style,
                flexDirection: 'row',
                flexWrap: 'wrap',
                backgroundColor: 'red',
                margin: Dimensions.generalPadding * 2,
            }}
        >
            <NativeTextView
                text={props.viewModel.aboutMeText}
                textColorString={Colors.red}
                backgroundColor={Colors.black}
                style={{
                    ...regularTextStyle,
                    width: "100%",
                    flexDirection: 'row',
                }}    />
        </View>
    )
}

On the native iOS side:


@objc(RNNativeTextView)
class NativeTextView: UITextView {
   ... (native implementation)
}
import Foundation

@objc(RNNativeTextViewManager)
class RNNativeTextViewManager: RCTViewManager {

    override func view() -> UIView! {

        let textView = NativeTextView(frame: CGRect(x: 0, y: 0, width: .zero, height: .zero))
        return textView
  }
}
#import <React/RCTBridgeModule.h>
#import <React/RCTViewManager.h>


@interface RCT_EXTERN_MODULE(RNNativeTextViewManager, RCTViewManager)

RCT_EXPORT_VIEW_PROPERTY(text, NSString)
RCT_EXPORT_VIEW_PROPERTY(textColorString, NSString)

+ (BOOL)requiresMainQueueSetup { return YES; }

@end

Like this no TextView is shown at all. This is so because the height of the NativeTextView is 0. If I put a static fixed height to the style, the NativeTextView is getting rendered like expected. But what I want is a dynamic height which depends on the text length of course.

Tried to find a solution on the dev-documentation but found nothing really helpful. Missed I something? How would be a good and efficient way to calculate the height of this UITextView?

0

There are 0 answers