【问题标题】:How to insert a UITableViewCell at bottom with animation?如何在底部插入带有动画的 UITableViewCell?
【发布时间】:2018-09-03 10:48:52
【问题描述】:

我已阅读https://stackoverflow.com/questions/

并尝试如下:

//UITableView 
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50;

//Update the full code for the "return" key action
- (void)inputViewDidTapReturn:(MyInputView *)inputView text:(NSString *)text{
    NSLog(@"send text-----%@",text);
    [self.messageManager sendMessageTo:self.sessionID message:text  completion:^(BOOL success, Message *message) {
        if (success) {

            [self.dataArray addObject:message];

            NSIndexPath * bottomIndexPath = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];

            [self.tableView beginUpdates];
            [self.tableView insertRowsAtIndexPaths:@[bottomIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];


            [self.tableView scrollToRowAtIndexPath:bottomIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

        } else {
        }
    }];
}

但是结果显示不正确:

它从屏幕底部开始滚动。

UITableViewUITableViewCell 都使用自动布局,UITableView 已经在键盘顶部。

任何帮助将不胜感激。

【问题讨论】:

    标签: ios uitableview autolayout ios-autolayout


    【解决方案1】:

    试试这个。

    目标 C

    [self.dataArray addObject:message];
    [self.tableView reloadData];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *bottomIndexPath = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:bottomIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
    

    输出

    斯威夫特

    self.dataArray.add(messasge)
    self.tableView.reloadData()
    
    DispatchQueue.main.async {
        let bottomIndexPath = IndexPath(row: self.dataArray.count-1, section: 0)
        self.tableView.scrollToRow(at: bottomIndexPath, at: .bottom, animated: true)
    }
    

    【讨论】:

    • 由于超出部分的范围而崩溃。添加 insert 方法后,它没有崩溃,但也没有工作。
    • @Kuldeep 你不认为 reloadData 也应该在主线程上完成吗?
    • @Kuldeep 它看起来更好但并不完美。 demo gif
    • @magic_9527,我认为你还在做其他事情。你能用按钮操作代码更新你的问题吗?
    • @Kuldeep 你好,我已经更新了UITableViewreturn function
    【解决方案2】:

    正确的方法是使用beginUpdatesendUpdates 方法将单元格插入到表格视图中。首先,您应该将项目添加到您的数组中。

    array.append(item)

    这不会更新表格视图,只更新数组,将单元格添加到视图中只需调用

    tableView.beginUpdates()
    tableView.insertRows(at: [IndexPath(row: array.count-1, section: 0)], with: .automatic)
    tableView.endUpdates()
    

    【讨论】:

    • 1 点 OP 需要 ObjectiveC 中的解决方案 2 点 您的代码不会自动移动到最新插入的行。
    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多