我正在为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