首页 > 解决方案 > 删除 UISearchBar 左右两边的空格

问题描述

我正在创建一个应该在下面显示 aUILabel和 a的 UI 组件UISearchBar

但是,我无法对齐它们,UISearchBar左侧和右侧总是有额外的空间(突出显示的红色)。

我试图直接设置searchBarTextField布局锚点的尺寸,但它没有用。

如果可能,我更愿意使用布局锚点。

SearchBar.m

-(id) init {        
    self.titleLabel = [UILabel new];
    self.searchBar = self.searchController.searchBar;
    UIView *searchBarWrapper = [UIView new];

    [self.view addSubview:self.titleLabel];
    [self.view addSubview:searchBarWrapper];
    [searchBarWrapper addSubview:self.searchBar];

    [self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
    [searchBarWrapper setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.searchBar setTranslatesAutoresizingMaskIntoConstraints:NO];

    //[self.titleLabel.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:1.0].active = YES;
    [self.titleLabel.heightAnchor constraintEqualToConstant:14.0].active = YES;
    [self.titleLabel.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
    [self.titleLabel.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
    [self.titleLabel.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
    //[self.titleLabel.bottomAnchor constraintEqualToAnchor:searchBarTextField.topAnchor].active = YES;

    [searchBarWrapper.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:1.0].active = YES;
    //[self.searchBar.heightAnchor constraintEqualToConstant:36.0].active = YES;
    [searchBarWrapper.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor].active = YES;
    [searchBarWrapper.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
    [searchBarWrapper.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
    [searchBarWrapper.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;

    [self.searchBar.topAnchor constraintEqualToAnchor:searchBarWrapper.topAnchor].active = YES;
    [self.searchBar.bottomAnchor constraintEqualToAnchor:searchBarWrapper.bottomAnchor].active = YES;
    [self.searchBar.leftAnchor constraintEqualToAnchor:searchBarWrapper.leftAnchor].active = YES;
    [self.searchBar.rightAnchor constraintEqualToAnchor:searchBarWrapper.rightAnchor constant:16.0].active = YES;

    return self;
}

左边和右边的空间高亮

UISearchBarTextField嵌入在UIView我无权访问的 a 中。

约束:

约束和视图层次结构

@BenOng 的方法 - 工作正常,但在第一次点击后中断:

窃听

标签: iosautolayoutuisearchbarlayout-anchornslayoutanchor

解决方案


UISearchBar 具有此属性searchFieldBackgroundPositionAdjustment:UIOffset,您可以将其设置为UIOffsetMake(-8,0)使文本字段的左侧与搜索栏的左边缘对齐。

在完整搜索栏应位于的位置创建一个 UIView,并将搜索栏设为子视图。将搜索栏的右边缘设置在它的超级视图之外,直到右边缘与超级视图对齐,它应该多出大约 16 个点。确保superview的属性clipsToBounds设置为true,额外的16点搜索栏背景将被剪掉。


推荐阅读