gpt4 book ai didi

react-native - 如何通知 React Native 自定义 View 的大小发生了变化?

转载 作者:行者123 更新时间:2023-12-03 12:24:20 25 4
gpt4 key购买 nike

我正在为 React Native iOS 编写自定义 View 。

基本上我必须使文本尽可能大(基于当前 View 的 View )。我已经通过覆盖 reactSetFrame 来完成它并改变框架。唯一的问题是 View 的位置是错误的,这是一个截图:

overlapping views

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

我试过调用 reactSetFrame再次使用新框架,但它无法正常工作。有没有办法告诉 React Native View 的大小发生了变化?

最佳答案

所以我终于找到了一种方法来做到这一点;基本上 react 原生利用阴影 View 来获取布局信息。所以我不得不将此代码添加到我的经理

- (RCTShadowView *)shadowView
{
return [FitTextShadowView new];
}

这基本上是在告诉我的组件的阴影 View 是什么。

然后我不得不更改 Yoga 使用的测量函数的实现,以获得正确的高度:

@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

关于react-native - 如何通知 React Native 自定义 View 的大小发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com