2024新iOS项目奇怪需求和遇到的坑记录

3,310 阅读1分钟

奇怪需求和遇到的坑

1、WebView 的高度不固定,需求是这样的:需要请求回来字符串,但字符串的长度不确定,WebView的高度需要随着字符串长度变化。
实现方式是使用 KVO 进行对 WebView 的scrollView.contentSize.height进行监听,然后更新约束。代码实现如下

- (void)setUpUI {
    
    // 监听内容高度变化
    [self.contentWeb.scrollView addObserver:self
                              forKeyPath:@"contentSize"
                                 options:NSKeyValueObservingOptionNew
                                 context:nil];
}

// 移除观察者
- (void)dealloc {
    [self.contentWeb.scrollView removeObserver:self forKeyPath:@"contentSize"];
}

// 监听内容高度变化
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGFloat height = self.contentWeb.scrollView.contentSize.height;
        
        // 避免无限循环更新
        if (height != self.contentWeb.frame.size.height) {
            [self.contentWeb mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(height).priorityLow();
            }];
            
            UITableView *tableView = (UITableView *)self.superview;
            while (tableView && ![tableView isKindOfClass:[UITableView class]]) {
                tableView = (UITableView *)tableView.superview;
            }
            
            if (tableView) {
                NSIndexPath *indexPath = [tableView indexPathForCell:self];
                if (indexPath) {
                    // 确保数据源已更新
                    [UIView performWithoutAnimation:^{
                        [tableView beginUpdates];
                        [tableView endUpdates];
                    }];
                }
            }
        }
    }
}

我的 WebView 是放在 TableView 中的,需要避免无限循环更新,否则内存会爆。
2、UITextView 高度不确定需求,和上面的 WebView 需求是一样的,直接上代码。


// 计算文本所需的高度
CGSize size = [titleData boundingRectWithSize:CGSizeMake(kWidth, MAXFLOAT)
                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]}
                                    context:nil].size;
    
    
CGFloat textViewHeight = size.height + 20;
    
[self.titleTextView mas_updateConstraints:^(MASConstraintMaker *make) {
    make.height.mas_equalTo(textViewHeight);
}];

总体来说比 WebView 简单很多

遇到的坑

1、记不清具体报错了,代码改回去也不报错,不知道为什么,是这样的情况

[(NSArray *)json[@"data"] count] == 0

我的json是字典类型,非让我转数组,可是字典也有count啊,欢迎大神们指教 2、Cell中的layoutSubviews谨慎使用手动布局,在有数据和无数据的UI效果不一样,具体原因不了解,仍然欢迎大神们指教