首页 > 解决方案 > Google Places iOS 自动填充结果空间

问题描述

我尝试使用 Google 的自动完成 API,并使用了本教程: https ://developers.google.com/places/ios-sdk/autocomplete#add_a_search_bar_to_the_top_of_a_view

我的 viewDidLoad 方法包含以下内容:

[super viewDidLoad];
// google autocomplete
_resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
_resultsViewController.delegate = self;
[_resultsViewController setExtendedLayoutIncludesOpaqueBars:YES];

_searchController = [[UISearchController alloc]
                     initWithSearchResultsController:_resultsViewController];
_searchController.searchResultsUpdater = _resultsViewController;

[_searchController setDelegate:self];

// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
self.definesPresentationContext = YES;

// Prevent the navigation bar from being hidden when searching.
_searchController.hidesNavigationBarDuringPresentation = NO;

self.navigationController.navigationBar.translucent = NO;
_searchController.hidesNavigationBarDuringPresentation = NO;

self.extendedLayoutIncludesOpaqueBars = YES;
self.edgesForExtendedLayout = UIRectEdgeTop;
[_searchBarContainerView addSubview:_searchController.searchBar];

[_searchController setActive:YES];

但它显示的结果就像图像上一样。如何删除结果和搜索栏之间的空格? 在此处输入图像描述

标签: iosobjective-cgoogle-places-api

解决方案


我通过执行以下操作设法解决了这两个问题:

首先,为您的实例设置.automaticallyAdjustsScrollViewInsets为:falseGMSAutocompleteResultsViewController()

resultsViewController.automaticallyAdjustsScrollViewInsets = false

如果您现在运行您的应用程序,您会看到多余的空间已经消失,但现在第一个结果在您的搜索栏下方。为了解决这个问题,我使用了该additionalSafeAreaInsets.top属性(我建议将其设置为您searchBarContainerView的高度,尽管您可以使用任何您想要的值):

resultsViewController.additionalSafeAreaInsets.top = searchBarContainer.frame.height

旁注:如果您支持 iOS 11 之前的设备,则必须将这些行包含在#available检查中,因为additionalSafeAreaInsets仅在 iOS 11+ 中可用。但是,在我自己的测试中,我发现 iOS 10 及更低版本一开始就没有这个问题。


推荐阅读