【问题标题】:Adding UISearchBar in UINavigationBar with constraints在带有约束的 UINavigationBar 中添加 UISearchBar
【发布时间】:2018-03-02 08:04:16
【问题描述】:

全部,

我想将 UISearchBar 添加到 UINavigationbar,我不想使用 UISearchController,只是以编程方式使用 UISearchbar,它也必须在横向中工作。

我试过它在纵向上运行良好,但在横向上,我在 iPhone X 宽度上遇到了问题。我们可以使用约束吗?

下面是代码

 CGFloat width = [UIScreen mainScreen].bounds.size.width;
    search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, width - 2 * 44 - 2 * 15, 44)];
    search.delegate = self; //    search.tintColor = [UIColor redColor];
    search.searchBarStyle = UISearchBarStyleMinimal;
    search.placeholder = @"Search";
    search.translucent = NO;
    search.opaque = NO;
    search.showsCancelButton = NO;
    [search setBackgroundImage:[[UIImage alloc] init]];

    //customize textfield inside UISearchBar
    @try {
        for (id object in [[[search subviews] firstObject] subviews])
        {
            if (object && [object isKindOfClass:[UITextField class]])
            {
                UITextField *textFieldObject = (UITextField *)object;
                textFieldObject.backgroundColor = [UIColor whiteColor];
                textFieldObject.borderStyle = UITextBorderStyleRoundedRect;
                textFieldObject.layer.borderColor = (__bridge CGColorRef _Nullable)([brandingObj getValueForKey:navBarTitleColor]);
                textFieldObject.layer.borderWidth = 1.0;
                break;
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"Error while customizing UISearchBar");
    }
    @finally {

    }

【问题讨论】:

    标签: objective-c uinavigationbar uisearchbar landscape-portrait


    【解决方案1】:

    我不明白你为什么要使用 UISearchDisplayController,它高度可配置并由苹果推荐,使用几何(CGRecr、CGFrame 等)来调整 UIKit 对象布局可能会很痛苦,使用自动布局避免 UIKit 的便利初始化器,以调整以后的约束。

    无论如何,如果您想明确地使用这种方式,这应该可行。

    #import "ViewController.h"
    
    @interface ViewController ()<UISearchBarDelegate>
        @property UISearchBar *searchbar;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        _searchbar = [UISearchBar new];
        _searchbar.delegate = self;
        _searchbar.searchBarStyle = UISearchBarStyleMinimal;
    
        self.navigationItem.titleView = self.searchbar;
        // Do any additional setup after loading the view, typically from a nib.
    }
    

    也许你需要配置外观,看看here

    干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多