Динамическая TextView высота внутри UITableViewCell KeyBoard избежать проблемы? - PullRequest
0 голосов
/ 28 мая 2019

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

Я пытаюсь получить TextView с Динамическая высота внутри пользовательского tableViewCell, который легко реализовать с помощью textView delegate TextChange, чтобы сообщить табличному виду start/end update и с UITableViewAutomaticDimension в табличном представлении heightForRowAtIndexPath делегатом. ячейка будет расширяться и уменьшаться зависит от текста, , но это не проблема,

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        return UITableViewAutomaticDimension;

}
   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{



    ExpandableTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExpandableTextTableViewCell_ID" forIndexPath:indexPath];
    cell.cellTextView.text = description;
    cell.cellTextView.tag = 2;
    [cell.cellTextView setFont:FONT_SS_REGULAR(18)];
    [cell.cellTextView setTextColor:[UIColor colorWithWhite:0.0 alpha:.7]];


    [cell setOnUpdateCellDescription:^(NSString * _Nonnull cellDescription) {
        description = cellDescription;



        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI on the main thread.
            [UIView setAnimationsEnabled:NO];

            [tableView beginUpdates];

            [tableView endUpdates];
            [UIView setAnimationsEnabled:YES];


        });


    }];

    return cell;

}

проблема, когда пользователь продолжает печатать, и для textView нет максимальной высоты , а не прокручивается , текст будет под клавиатурой. Вы можете увидеть в первом Gif.

enter image description here

Итак, я попробовал все:

1 - изменение вида таблицы Bottom constraint.

2- TPkeyboardavoidingtableview.

3- IQkeyboardManagers.

4- Сделайте мой собственный расчет, чтобы изменить content size

и для каждого решения Tableview начнет прыгать как сумасшедший, см. Второй рисунок.

enter image description here

Всем, кто опубликует эту ссылку динамическую высоту ячейки в качестве решения, я хотел бы сообщить ему, что это решение построено на основе UITableViewController, а не UIViewController.

ОБНОВЛЕНИЕ № 1

Я попытался остановить анимацию перед beginUpdates / endUpdates, как показано ниже, и прыжки исчезают, когда начинают заполнять текстовое представление в первый раз, но когда удаляют весь текст и пытаются заполнить его снова, избегание остановки клавиатуры:

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update the UI on the main thread.
                [UIView setAnimationsEnabled:NO];

                [tableView beginUpdates];

                [tableView endUpdates];
                [UIView setAnimationsEnabled:YES];


            });

1 Ответ

0 голосов
/ 28 мая 2019

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

скажем:

protocol CustomTableViewCellDelegate: NSObjectProtocol {
     func customTableViewCellDidBeginEditing(at indexPath: IndexPath, didFinish: Bool)
}

и в клетке это будет, как вы знаете:

weak var delegate: CustomTableViewCellDelegate?
var cellIndexPath: IndexPath!

При снятии очереди с ячейки на контроллере представления:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
        cell.cellIndexPath = indexPath
        cell.delegate = self

        return cell
}

Когда текст начинает меняться, вам нужно вызвать делегата:

self.delegate?.customTableViewCellDidBeginEditing(at: self.cellIndexPath, didFinish: false)

в случае ячейки с текстовым представлением вы хотите вызвать ее, когда это включено:

func textViewDidChange(_ textView: UITextView) {
    self.delegate?.customTableViewCellDidBeginEditing(at: self.cellIndexPath, didFinish: false)
}

func textViewDidBeginEditing(_ textView: UITextView) {
    self.delegate?.customTableViewCellDidBeginEditing(at: self.cellIndexPath, didFinish: false)
}

И когда текст закончится, вам нужно вызвать делегата:

self.delegate?.customTableViewCellDidBeginEditing(at: self.cellIndexPath, didFinish: true)

в случае ячейки с текстовым представлением, которую вы хотите вызвать, когда это включено:

func textViewDidEndEditing(_ textView: UITextView) {
    self.delegate?.customTableViewCellDidBeginEditing(at: self.cellIndexPath, didFinish: true)
}

На стороне контроллера View:

extension ViewController: CustomTableViewCellDelegate {

func customTableViewCellDidBeginEditing(at indexPath: IndexPath, didFinish: Bool) {

    // Let assume the Keyboard height is 260 or you can listen to the keyboardWillShowNotification and get the keyboardFrame.cgRectValue.height
    let keyboardHeight = 260
    self.tableView.contentInset.bottom = didFinish ? keyboardHeight : 0
    self.tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: true)
}
}

Наслаждайтесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...