Add*_*dev 2 xcode objective-c interface-builder ios
我正在尝试在我的应用程序 UI 中放置一个 UISearchController。布局是:
我想将 UISearchController 的 UISearchView 放在黑色容器中。
我的代码如下:
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsViewController];
UISearchBar* searchBar = self.searchController.searchBar;
searchBar.frame =_searchBarContainer.bounds;
[_searchBarContainer addSubview:searchBar];
[_searchBarContainer layoutIfNeeded];
Run Code Online (Sandbox Code Playgroud)
它将 UISearchBar 放置在正确的位置:
但是当我选择搜索字段时,它会将栏扩展到容器的边界上:
如何解决这个问题并避免选择时的尺寸/外观变化?
注意:尝试了一些使用translatesAutoresizingMaskIntoConstraints和 的 clipToBounds选项,但没有成功。我不是 iOS UI 的专家,所以我希望得到准确的答案。谢谢
根据我的研究,每次选择 时SearchBar,UISearchController都会显示一个。这UISearchController总是试图使searchBar的宽度等于UIViewController呈现的宽度UISearchController。
我的解决方案是当UISearchControllermakeSearchBar有错误的框架时,SearchBar再次设置'frame。您可以在下面尝试此代码。
@interface ViewController () <UISearchControllerDelegate>
@property (nonatomic, strong) UISearchController* searchController;
@property (weak, nonatomic) IBOutlet UIView *searchBarContainer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsViewController];
UISearchBar* searchBar = self.searchController.searchBar;
self.searchController.delegate = self;
searchBar.frame =_searchBarContainer.bounds;
[_searchBarContainer addSubview:searchBar];
[_searchBarContainer layoutIfNeeded];
}
- (void)willPresentSearchController:(UISearchController *)searchController {
[searchController.searchBar addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)willDismissSearchController:(UISearchController *)searchController{
[searchController.searchBar removeObserver:self forKeyPath:@"frame"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (object == self.searchController.searchBar) {
if (!CGSizeEqualToSize(self.searchController.searchBar.frame.size, _searchBarContainer.frame.size)) {
self.searchController.searchBar.superview.clipsToBounds = NO;
self.searchController.searchBar.frame = CGRectMake(0, 0, _searchBarContainer.frame.size.width, _searchBarContainer.frame.size.height);
}
}
}
@end
Run Code Online (Sandbox Code Playgroud)
至少,它有效:)
或者
UIViewController包含SearchBar在此之后将其添加到 _searchBarContainer 的内容。UISearchBar和UITableView代替UISearchController。更容易处理。| 归档时间: |
|
| 查看次数: |
853 次 |
| 最近记录: |