繁体   English   中英

永久设置 UITableView 内容插入

[英]Set UITableView content inset permanently

在我的应用程序中,我在UINavigationBar下有一个UISearchBar ,因此它始终对用户可见。 在这种情况下,我必须将contentInset设置为额外的 44px,以便UIScrollView将在UISearchBar下滚动(就像在 Contacts.app 中一样) 静态UITableView没有问题,但在我的情况下,我必须重新加载它的内容,切换到UISearchDisplayController等。所以当我打电话时:

[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];

一切正常,直到例如我拉刷新...(为此我使用SSPullToRefresh )。

所以我的问题是:如何永久设置contentInset这样我就不必担心UITableView数据发生任何变化?

可能这是我的某种错误,因为我弄乱了自动布局和故事板,但我找到了答案。

你要在View Controller's Attribute Inspector中照顾这个小家伙阿维

必须取消选中它,以便在任何更改后不会设置默认的contentInset 之后,它只是向viewDidLoad添加一行代码:

[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)]; // 108 is only example

iOS 11、Xcode 9 更新

如果涉及到iOS 11Xcode 9 ,看起来以前的解决方案不再是正确的解决方案。 automaticallyAdjustsScrollViewInsets已被弃用,现在要实现类似的效果,您必须转到Size Inspector ,在那里您可以找到: 在此处输入图片说明
此外,您可以在代码中实现相同的功能:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

在斯威夫特:

override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      self.tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
}

AutomaticAdjustsScrollViewInsets 在 iOS11 中已弃用(并且已接受的解决方案不再有效)。 用:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

添加 numberOfRowsInSection 你的代码[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)]; . 因此,您将始终设置 contentInset 重新加载表中的数据

经过一小时的测试,100% 工作的唯一方法是:

-(void)hideSearchBar
{
    if([self.tableSearchBar.text length]<=0 && !self.tableSearchBar.isFirstResponder)
    {
        self.tableView.contentOffset = CGPointMake(0, self.tableSearchBar.bounds.size.height);
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

-(void)viewDidLayoutSubviews
{
    [self hideSearchBar];
}

使用这种方法,如果搜索栏为空,您可以随时隐藏搜索栏

这是通过 Storyboard(iOS 11 和 Xcode 9.1)轻松修复的方法:

选择表格视图 > 尺寸检查器 > 内容插入:从不

尝试设置 tableFooterView tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))

      self.rx.viewDidAppearOnce
            .flatMapLatest { _ in RxKeyboard.instance.isHidden }
            .bind(onNext: { [unowned self] isHidden in
                guard !isHidden else { return }
                self.tableView.beginUpdates()
                self.tableView.contentInsetAdjustmentBehavior = .automatic
                self.tableView.endUpdates()
            })
            .disposed(by: self.disposeBag)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM