ios - 重新加载 UITableView 会在动画后重置帧

标签 ios objective-c uitableview uisearchbar

我一直被这个问题困住,我真的很好奇为什么会这样。我使用如下所示的简单示例重新创建了我的问题。我在 View 底部放置了一个带有自定义 UITableViewCell(在单元格中心包含一个 UILabel)的 UITableView,在顶部放置了一个 UISearchBar。

当键盘弹出时,我为 UITableView 设置动画以更改其框架以适应 UISearchBar 下方和键盘上方的空间。现在,当我输入任何搜索文本并重新加载 UITableView 时,UITableView 会在动画之前更改其框架。

最初-

UITableView Frame: {{0, 223}, {320, 237}} - {{x, y},{width, height}}

动画之后-

UITableView Frame: {{0, 44}, {320, 436}} - {(x, y),(width, height)}

当我输入任何搜索文本时 - UITableView Frame: {{0, 223}, {320, 237}} - {{x, y},{width, height}}

我注意到这只发生在自定义 UITableViewCell 上。我四处寻找答案,但一无所获。我尝试将 UILabel 作为 subview 添加到自定义 UITableViewCell 中的 contentView,但这没有用。所以我的问题是,如何防止 UITableView 将其框架恢复为原始值?

编辑:这是我在动画后更改 UITableView 框架的代码。

- (void)keyboardDisplayed:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardValue = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrame = [keyboardValue CGRectValue];

    CGRect frame = self.testTabl.frame;
    frame.origin.y = self.testSearchBar.frame.origin.y + self.testSearchBar.frame.size.height;
    frame.size.height = keyboardFrame.origin.y - frame.origin.y;

    [UIView animateWithDuration:0.3 animations:^{
        [self.testTabl setFrame:frame];
    }];

    NSLog(@"TableView Frame: %@", NSStringFromCGRect(self.testTabl.frame));
}

最佳答案

我不确定它是否解释了您所看到的行为,但您代码中的主要问题是您需要改用 UIKeyboardFrameEndUserInfoKey。像下面这样的东西应该可以工作:

- (void)keyboardDisplayed:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    CGPoint endPoint = [[keyboardInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin;
    CGFloat duration = [[keyboardInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];

    CGRect frame = self.testTabl.frame;
    frame.size.height = [self.testTabl convertPoint:endPoint fromView:nil].y;

    [UIView animateWithDuration:duration animations:^{
        [self.testTabl setFrame:frame];
    }];

    NSLog(@"TableView Frame: %@", NSStringFromCGRect(self.testTabl.frame));
}

关于ios - 重新加载 UITableView 会在动画后重置帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010312/

相关文章:

iphone - 当推送一个新的 Controller 时,pushViewController 是否应该释放 oldController?

ios - UILabel 不会在 UIView 中居中

iphone - 更改数据源后 UITableView 无法正确刷新

ios - 以编程方式创建静态 TableView/单元格

iphone - 带有工厂方法的 Objective C 类继承

swift - 以编程方式从主线程以外的其他地方选择 UITableView 行

ios - 使用 coreData 中的关系快速获取数据

ios - 如何使用 Swift 以编程方式确定最新的 iOS 版本?

ios - 在两个 Action 之间随机选择并每隔一定时间重复一次

ios - i386/armv7 架构的 undefined symbol [cocoapods]