Повторное представление кадра ячейки collectionView вызывает рост памяти? - PullRequest
0 голосов
/ 02 мая 2018

Я работаю над пользовательским приложением клавиатуры и столкнулся с трудной проблемой. Я поинтересовался некоторыми документами, но, к сожалению, не нашел ответа. Я хочу попросить всех помочь мне.

Проблема в том, что когда я набираю на клавиатуре, результаты ввода будут отображаться в столбце кандидатов. Я использую UICollectionView для создания столбца кандидатов.

- (void)createCandideteColection {
    if (!_collectionView) {
        CGFloat height = self.frame.size.height-pinyinHeight-lineHeight; 
        CGFloat y = pinyinHeight+lineHeight; 
        CGFloat showButtonH = height; 
        CGFloat candidateShowWidth = self.frame.size.width - showButtonH;

        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal; 
        flow.minimumInteritemSpacing = 20; 
        flow.minimumLineSpacing = 20;

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, y, candidateShowWidth, height) collectionViewLayout:flow];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.bounces = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[GZCandidateCell class] forCellWithReuseIdentifier:@"candidateCell"];
        [self addSubview:_collectionView];
    }
}

Устанавливает рамку ячейки, _данные изменяются с вводом (каждый раз, когда вводится текст, _data изменяется один раз и [collectionView reloadData] вызывается один раз). Ширина ячейки изменяется в зависимости от количества введенных символов.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = _data[indexPath.row];
    CGFloat height = self.frame.size.height-pinyinHeight-lineHeight; 
    CGFloat width = str.length * 20 + 10;
    return CGSizeMake(width, height);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GZCandidateCell *cell = (GZCandidateCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"candidateCell" forIndexPath:indexPath];
    NSString *str = _data[indexPath.row];
    [cell setTitleText:str];
    return cell;
}

Назначить titleLabel значение, titleLabel размер будет пересчитан при вызове [cell setTitleText: str] .

когда [collectionView removeFromSuperview] вызывается, collectionView будет уничтожен, но имеется мало памяти, которая не может быть освобождена. Каждый раз, когда ввод завершается, и collectionView удалено, часть памяти не будет освобождена и станет больше после накопления.

Причина, по которой я в конечном итоге найду эту проблему в collectionView, заключается в том, что я не создаю этот collectionView, память не увеличивается.

Получите входные данные и покажите в collectionView и tabBar - столбец кандидатов, о котором я упоминал выше:

if (!_textKeyboard) {
    _textKeyboard = [[GZQwertyKeyboard alloc] initWithFrame:CGRectMake(0, navigaitonHeight, SCREEN_WIDTH, height) andKeyboardType:type];
    _textKeyboard.backgroundColor = Color_background_kb;
    [self.view addSubview:_textKeyboard];
}
__weak KeyboardViewController *weakSelf = self;
__weak GZQwerty *getdata = [GZQwerty defaultQwerty]; //init qwerty

_textKeyboard.sendSelectedStr = ^(NSString *text) {
    if (!weakSelf.tabBar) {
        [weakSelf addCandidateBarView];
    }

    int asciiCode = [text characterAtIndex:0];
    [getdata sendInput:asciiCode complation:^(NSString *compontText, NSArray *candiateArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [weakSelf.tabBar changeShowText:candiateArray];
        });
    }];
};

Вызовите [weakSelf addCandidateBarView] , чтобы создать tabBar .Call [weakSelf.tabBar changeShowText: CandiateArray] , чтобы изменить источник данных collectionView и обновить collectionView . Нравится это:

- (void)changeShowText:(NSArray*)textArr {
    _data = textArr;
    if (!_collectionView) {
        [self createCandideteColection];
    }
    [_collectionView reloadData];
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

Когда набирается клавиатура, если changeShowText: не вызывается, память стабильна и объем памяти не увеличивается.

Так, кто-нибудь может мне помочь? Есть ли лучший способ, чем collectionView или как избежать роста памяти? Это вызвано многократными изменениями ширины ячейки?

...